Variables and Data Types
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.
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;
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.
Primitive vs. Reference Types
Java has two main categories of data types. Think of it as having two different sections in your warehouse.
- 1Primitive TypesThese 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.
- 2Reference TypesThese 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 forCounting 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;.
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 forMeasurements 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 forAnswering 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 likeint,double, orboolean.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, notMyScore).=: 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.
See it in action
Worked examples
Let's walk through a couple of scenarios to see how to choose the right data type and declare variables.
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:
- The number of miles they ran, which might be a fraction (e.g., 4.5 miles).
- The total number of steps they took (always a whole number).
- Whether they met their daily step goal.
Solution Walkthrough:
- 1Analyze the "miles ran" dataThe problem states this could be a fraction, like 4.5. Whole numbers (
int) can't store decimals. Therefore, we must use adouble. Let's name our variablemilesRan.double milesRan = 4.5; - 2Analyze the "steps taken" dataSteps 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; - 3Analyze the "met goal" dataThe 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 itdidMeetGoal. Let's say the goal was 8,000 steps. Since 8,142 is greater than 8,000, the value istrue.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.
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:
- The price of a book, which is $14.99.
- The quantity of that book the customer wants (e.g., 2 copies).
- Whether the book is eligible for free shipping.
Solution Walkthrough:
- 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;
- 1Analyze the quantityA customer can't order 2.5 books. They order a whole number of items. So,
intis the correct choice.int quantity = 2; - 2Analyze shipping eligibilityIs it eligible? Yes or no. This is a binary choice, which means
booleanis 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.
Practice — 8 questions
In simple terms, variables are like labeled boxes for storing different types of information in your code, such as numbers or true/false values.
int playerScore;
int numberOfStudents;
- 1.2.A: Identify the most appropriate data type category for a particular specification.
- 1.2.B: Develop code to declare variables to store numbers and Boolean values.
- 1.2.A.1
- A data type is a set of values and a corresponding set of operations on those values. Data types can be categorized as either primitive or reference.
- 1.2.A.2
- The primitive data types used in this course define the set of values and corresponding operations on those values for numbers and Boolean values.
- 1.2.A.3
- A reference type is used to define objects that are not primitive types.
- 1.2.B.1
- The three primitive data types used in this course are int, double, and boolean. An int value is an integer. A double value is a real number. A boolean value is either true or false.
- 1.2.B.2
- A variable is a storage location that holds a value, which can change while the program is running. Every variable has a name and an associated data type. A variable of a primitive type holds a primitive value from that type.
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;
Read what Saavi narrates
Hey everyone, it's Saavi. Let's talk about one of the first things you do in any program: storing information.
Imagine you're building an app to track your progress in a video game. You need to remember your score, say 1,500 points... your health, maybe 85.5 percent... and whether you've found the secret key, which is a simple yes or no.
How does the computer know the difference between a whole number, a decimal, and a yes/no answer? Well, you have to tell it. This is where variables and data types come in. A variable is just a labeled storage spot for a piece of data. The data type tells the computer what *kind* of data is allowed in that spot.
At its core, this is about giving your data a home. You create a named spot, called a variable, and you define what kind of information can live there.
Let's walk through an example. Say we're creating a digital profile for a student, Maya. We need to store her grade level, her GPA, and whether she's on the honor roll.
First, her grade level. Let's say she's in 11th grade. That's a whole number, right? You can't be in grade 11.5. So, we use the `int` data type, for integers. We'd write code that says, in effect, "create an integer variable called gradeLevel and set it to 11".
Next, her GPA. A GPA is almost always a decimal, like 3.9. An `int` can't hold that, it would chop off the point-nine. So we need a different type: `double`. A `double` is perfect for any number with a decimal point. So we'd say, "create a double variable called gpa and set it to 3.9".
Finally, is she on the honor roll? That's a simple yes or no question. For this, we use the `boolean` data type, which can only be `true` or `false`. We'd write, "create a boolean variable called isOnHonorRoll and set it to true".
The most common mistake I see here is using `int` when you should use `double`. If you're calculating an average, or working with money, or anything that might have a fraction... use a `double`. If you use an `int`, your program will have bugs because it's losing information.
So, remember to think about the *nature* of the data you're storing. Is it a counter? Use an `int`. Is it a measurement? Use a `double`. Is it a yes/no question? Use a `boolean`. You've got this!
`int` truncates (chops off) the decimal part, not rounds it. Storing `19.99` in an `int` variable results in the value `19`, leading to incorrect calculations.
If a value could ever have a fractional part, use `double`. For example, `double price = 19.99;`.
The semicolon tells the Java compiler that the statement is finished. Without it, the compiler gets confused and throws an error, often complaining about the *next* line of code.
Mentally check for a semicolon at the end of every complete statement: `int score = 100;`.
In American English and in Java syntax, the period (`.`) is the decimal separator. A comma is used to separate items in a list, so `double value = 14,99;` is a syntax error.
Always use a period for decimal numbers: `double price = 14.99;`.
`"true"` is a `String` (a piece of text), not a `boolean` value. The variable `boolean isLoggedIn = "true";` will cause a type mismatch error.
Use the keywords `true` and `false` directly, without quotes: `boolean isLoggedIn = true;`.
Words like `int`, `double`, `boolean`, `class`, and `public` have special meanings in Java. You can't use them as names for your variables. `int double = 5;` is invalid.
Choose a descriptive name that isn't a reserved keyword. `int doubleValue = 5;` is perfectly fine.
Java is case-sensitive. The variable `playerScore` is completely different from `playerscore`. If you initialize `playerScore` and later try to use `playerscore`, the compiler will say it can't find the variable.
Stick to a consistent naming convention. The standard is camelCase, where the first word is lowercase and subsequent words are capitalized: `int myHighScore = 0;`.