Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Variables and Data Types

Lesson ~10 min read 8 MCQs

In simple terms: In simple terms, variables are like labeled boxes for storing different types of information in your code, such as numbers or true/false values.

Why this matters

Imagine you're building a simple app to track your progress in a video game. You need to remember your score, how much health you have left, and whether you've found the secret key. Your score is a whole number, like 1,500. Your health might be a percentage, like 85.5%. And whether you have the key is a simple yes or no.

How does the computer know the difference between these pieces of information? It can't just guess. You have to tell it exactly what kind of data you're storing. This is the first, most fundamental step in programming: creating labeled containers for your data and telling the computer what type of data goes inside. In this lesson, we'll learn how to create those containers, called variables, and choose the right data types for them.

Comparing different data types for game statistics.

Concept overview

flowchart TD
    A[Start: I need to store a value] --> B{What kind of value is it?};
    B --> C[A whole number?];
    C --> D[Use int];
    B --> E[A number with a decimal?];
    E --> F[Use double];
    B --> G[A true/false condition?];
    G --> H[Use boolean];
    D --> I[End];
    F --> I;
    H --> I;
This diagram is a flowchart that helps a user decide which Java primitive data type to use. It starts with the question "What kind of value is it?" and branches into three paths: "A whole number?" leads to "Use int", "A number with a decimal?" leads to "Use double", and "A true/false condition?" leads to "Use boolean". All paths lead to an "End" node.

Core explanation

Welcome to one of the most important building blocks in all of programming! Before a computer can do anything interesting, it needs to be able to store and manage information. We do this using variables and data types.

The Labeled Storage Bin Analogy

Think of your computer's memory as a massive, empty warehouse. If you just throw things in randomly, you'll never find them again. To stay organized, you use storage bins. You put a label on each bin ("Holiday Decorations", "Old T-Shirts") and you only put the correct type of item inside.

In Java, a variable is like that labeled storage bin. It's a named location in memory that holds a value. The data type is the rule that says what kind of value can go in the bin. You can't put a bowling ball in a bin meant for tiny screws, and you can't put a decimal number in a variable meant for a whole number.

Variables as labeled storage bins in memory.

Primitive vs. Reference Types

Java has two main categories of data types. Think of it as having two different sections in your warehouse.

  1. 1
    Primitive Types
    These are the most basic, fundamental data types. They are like the simple, standard-issue bins for holding one single thing: a number, a single character, or a true/false value. They are simple, efficient, and built directly into the Java language.
  2. 2
    Reference Types
    These are for storing more complex information. A reference variable is like a bin that doesn't hold the object itself, but instead holds a piece of paper with the address of where to find a bigger, more complicated object elsewhere in the warehouse. Objects like String (for text), Scanner (for user input), or custom objects you build yourself are all reference types.

For this unit, we are laser-focused on the primitive types. We'll get to the power of reference types very soon!

The Three Essential Primitive Types

The AP Computer Science A exam requires you to master three specific primitive data types. Let's break them down.

1. int for Integers

The int data type is for storing integers—that is, positive or negative whole numbers without any decimal points.

  • Use it for
    Counting things, like the number of players on a team, a score in a game, your age in years, or the year you were born.
  • Examples
    -5, 0, 42, 2024

To create a variable, you first declare it. This is like putting an empty, labeled bin on the shelf. The syntax is type name;.

Declaring and initializing `int` variables.
int playerScore;
int numberOfStudents;

Then, you can initialize it by giving it a value using the equals sign (=), which is the assignment operator.

playerScore = 1500;
numberOfStudents = 28;

You can also declare and initialize a variable in a single line, which is very common.

int currentYear = 2024;

2. double for Decimal Numbers

The double data type is for storing floating-point numbers—that is, numbers that have a fractional part or decimal point. The name "double" comes from the fact that it uses twice the memory (double the precision) of an older type called float.

  • Use it for
    Measurements that can be fractional, like a person's height in meters, a GPA, a price, or a temperature.
  • Examples
    -1.5, 0.0, 98.6, 3.14159
double accountBalance = 120.75;
double gpa = 3.8;

3. boolean for True or False

The boolean data type is the simplest. It can only hold one of two possible values: true or false. That's it. It's named after George Boole, an English mathematician who created a system of logic based on these two values.

  • Use it for
    Answering any yes/no question. Is the game over? Is the user logged in? Is the light switch on?
  • Examples
    true, false
boolean isGameOver = false;
boolean hasCompletedAssignment = true;

Putting It All Together

Every variable you create must follow this pattern:

dataType variableName = value;

  • dataType: One of the keywords like int, double, or boolean.
  • variableName: A name you choose. It must start with a letter, _, or $, and can't be a reserved Java keyword. By convention, we start variable names with a lowercase letter (e.g., myScore, not MyScore).
  • =: The assignment operator. It takes the value on the right and stores it in the variable on the left.
  • value: A value that matches the data type.
  • ;: The semicolon. Every statement in Java ends with a semicolon. It's like the period at the end of a sentence. Don't forget it!

Now you have the tools to tell your program what to remember and how to store it correctly.

Primitive vs. Reference Data Types in Java.

See it in action

python
Line 1
Output
Click Run to see the output.

        
Try these
    © Shrutam.ai

    Worked examples

    Let's walk through a couple of scenarios to see how to choose the right data type and declare variables.

    Example 1

    Tracking a Runner's Stats

    Problem: You're writing a program for a fitness app. You need to store the following information about a runner's latest session:

    1. The number of miles they ran, which might be a fraction (e.g., 4.5 miles).
    2. The total number of steps they took (always a whole number).
    3. Whether they met their daily step goal.

    Solution Walkthrough:

    1. 1
      Analyze the "miles ran" data
      The problem states this could be a fraction, like 4.5. Whole numbers (int) can't store decimals. Therefore, we must use a double. Let's name our variable milesRan.
      double milesRan = 4.5;
    2. 2
      Analyze the "steps taken" data
      Steps are counted one by one. You can't take half a step. This is a classic case for an integer. We'll name the variable stepsTaken.
      int stepsTaken = 8142;
    3. 3
      Analyze the "met goal" data
      The question is "Did they meet the goal?" The answer is either yes or no. This is a perfect fit for a boolean. We'll name it didMeetGoal. Let's say the goal was 8,000 steps. Since 8,142 is greater than 8,000, the value is true.
      boolean didMeetGoal = true;

    Why it matters: If you had chosen int for milesRan, the value 4.5 would have been stored as 4, and your app's calculations would be wrong. Choosing the correct data type from the start is crucial for accuracy.


    Example 2

    Online Shopping Cart

    Problem: You're coding a piece of an e-commerce site for a bookstore in Chicago. You need to declare variables to store information for a single item in a shopping cart:

    1. The price of a book, which is $14.99.
    2. The quantity of that book the customer wants (e.g., 2 copies).
    3. Whether the book is eligible for free shipping.

    Solution Walkthrough:

    1. Analyze the price: Money involves dollars and cents, so it has a decimal point. This immediately tells you to use double.
      double bookPrice = 14.99;
    The common mistake of using `int` for monetary values.
    1. 1
      Analyze the quantity
      A customer can't order 2.5 books. They order a whole number of items. So, int is the correct choice.
      int quantity = 2;
    2. 2
      Analyze shipping eligibility
      Is it eligible? Yes or no. This is a binary choice, which means boolean is the perfect tool for the job.
      boolean isShippingFree = false;

    By correctly identifying the nature of each piece of data, you can write clear, correct, and bug-free code.

    Try it yourself

    Time to practice! Read the scenarios below and write the Java code to declare and initialize a variable for each piece of information.

    Problem 1: Student ID Card

    You're creating a digital student ID for a school in Dallas. You need variables for:

    • The student's grade level (e.g., 9, 10, 11, 12).
    • Their current lunch balance (e.g., $5.50).
    • Whether they are permitted to leave campus for lunch.

    Problem 2: Weather App

    You're coding a simple weather display for Boston. You need variables for:

    • The current temperature in Fahrenheit, which might be 67.8.
    • The chance of rain as a whole number percentage, like 40.
    • Whether there is a severe weather alert currently active.
    Variables for a Student ID Card.
    Variables for a Weather App.