AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/1/1-2)
Unit 1 · Topic 1.2
1.2 Variables and Data Types
Every value in Java has a type, and the type decides what values are allowed and what you can do with them. This topic introduces the three primitive types you'll use all year, int, double and boolean, and the idea of a variable as a named place to store a value.
Key terms
- data type
- primitive type
- reference type
intdoubleboolean- variable
What a data type is
A data type is two things together: a set of allowed values and the operations that work on them. An int can hold 42 and can be added, subtracted and so on; a boolean can only be true or false, and you combine booleans with logic instead of arithmetic.
Java sorts types into two groups. Primitive types are the simple built-in types that hold a single value directly. Reference types are everything else: String, Scanner, ArrayList and any class you or someone else writes. A reference type describes objects, and you'll learn how they're stored in 1.12.
The three primitive types in this course
| Type | Holds | Examples |
|---|---|---|
| int | Whole numbers (integers), positive, negative or zero | 0, -12, 2026 |
| double | Real numbers, which can have a decimal part | 3.14, -0.5, 7.0 |
| boolean | One of two values | true, false |
Variables
A variable is a named storage location. When you declare one, you give its type and its name, and you usually give it a starting value too:
int score = 0;
score = 15;
double temperature = 71.5;
boolean isRaining = true;
Each variable keeps its type forever, but its value can change while the program runs. After the second line, score holds 15, not 0. A variable of a primitive type stores the value itself.
Naming rules: a name starts with a letter, has no spaces, and can't be a Java keyword like int or class. Names are case-sensitive, so score and Score are different variables. Java programmers write multi-word names in camelCase, like stepsToday, and pick names that say what the value means.
Choosing the right type
Questions often describe some data and ask which type fits best. Ask yourself what the value looks like:
- Something you count, like a number of students, points or steps:
int. - A measurement that can have a fractional part, like a price, distance, temperature or average:
double. - A yes-or-no fact, like whether a door is locked or a game is over:
boolean. - Text, like a name or a sentence:
String, which is a reference type, not a primitive.
Not on the exam
Java has five more primitive types: long, short, byte, float and char. You won't be tested on any of them, so stick with int, double and boolean.
Worked examples
Try each one yourself first, then open the solution.
- Example 1
Picking types for a fitness app
A fitness app tracks the number of steps a user takes today, the distance they walked in miles, whether they reached their daily goal, and their name. Declare a variable for each, then record that the goal has now been met and print everything. One correct answer:
int stepsToday = 8250; double milesWalked = 3.6; boolean goalMet = false; String userName = "Maya"; goalMet = true; System.out.println(userName + " " + stepsToday + " " + milesWalked + " " + goalMet);Show the solutionHide the solution
- Step 1: Steps are counted one at a time and are always whole numbers, so
stepsTodayis anint. - Step 2: Distance can be 3.6 miles, which has a decimal part, so
milesWalkedis adouble. - Step 3: Reaching the goal is yes or no, so
goalMetis aboolean. It starts asfalse, and the fifth line changes it totrue. Notice there's no type on that line: you only state the type when you declare the variable. - Step 4: A name is text, so
userNameis aString, a reference type. - Step 5: The
+signs join the values into one string with spaces between them (more on that in 1.3 and 1.15).
Answer: Use
intfor steps,doublefor miles,booleanfor the goal andStringfor the name. The code printsMaya 8250 3.6 true. - Step 1: Steps are counted one at a time and are always whole numbers, so
- Example 2
Spotting a type mismatch
Will this declaration compile?
int count = 3.5;Show the solutionHide the solution
- Step 1: The variable is declared as an
int, so it can only hold whole numbers. - Step 2: The value 3.5 is a
double. Storing it in anintwould lose the .5, and Java won't do that silently. - Step 3: The compiler reports an error ("possible lossy conversion from double to int"), so this is a syntax error and the program won't run.
Answer: No. It doesn't compile, because a
doublevalue can't be stored in anintvariable without a cast (see 1.5). - Step 1: The variable is declared as an
Common mistakes
- Using
intfor a value that can have a decimal part, like a price or an average. The decimal part will be lost or the code won't compile. - Putting the type in front of a variable every time you use it.
int score = 0;declares it; after that, writescore = 15;. Writingint score = 15;again in the same block is a compile error. - Treating
Stringas a primitive type. It's a reference type (a class), which is why it has methods likelength().
On the exam
- Expect questions that describe data and ask for the most appropriate type, or that ask which declaration compiles. Match counts to
int, measurements todoubleand yes-or-no facts toboolean. - On free-response questions, declare each local variable with the right type before you use it, and reuse the names the question gives you.
Connected topics
Videos
Check yourself
4 questions on 1.2 Variables and Data Types. Pick an answer to see if you got it, and why.
Which of the following declarations compiles without error?
A program needs to store whether a library book is currently checked out. Which variable declaration is the best choice?
Which of the following variables holds a reference to an object rather than a primitive value?
Consider the following code segment.int points = 12;
points = 20;
double rate = points;
System.out.println(points + " " + rate);What is printed as a result of executing the code segment?
0 of 4 answered