Lesson 1.2 · Unit 1 · CED topic 1.2
Variables and data types
A variable is a named storage location that holds a value. In Java every variable has a name and a data type, and the type is permanent: a variable declared to hold whole numbers holds whole numbers for its whole life. The compiler enforces that promise, which is why so many Java mistakes are caught before the program ever runs.
A data type is a set of values together with the operations you can perform on those values. Java sorts data types into two categories. Primitive types hold a single plain value. Reference types define objects, and a variable of a reference type holds a reference to an object stored elsewhere.
Learning objectives.
- 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.
Essential knowledge.
- 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.
Outside the course: The other five primitive data types (long, short, byte, float, and char) are outside the scope of the AP Computer Science A course and exam. - 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.
The three primitive types in this course
| Type | Values | Examples of literals | Typical use |
|---|---|---|---|
int | whole numbers, positive, negative, or zero | 0, 42, -7 | counting, indexes, ages, scores |
double | real numbers, with a fractional part | 3.14, -0.5, 2.0 | measurements, averages, prices |
boolean | exactly true or false | true, false | yes or no questions, conditions |
7 and 7.0 are different values of different types. They print differently, they divide differently (Lesson 1.3 shows how), and they are stored differently. String is the reference type you meet first: a variable of type String holds a reference to a sequence of characters, and you write one in double quotes.
Declaring and initializing
A declaration gives a variable a type and a name. An initialization gives it its first value; you can do both in one statement.
int quantity = 3; // whole number double unitPrice = 12.50; // number with a fractional part boolean taxExempt = false; // exactly true or false String itemName = "Notebook"; // reference type: a String object
Names follow rules and habits.
- A name starts with a letter and contains letters, digits, and underscores.
quantityanditem2are valid;2ndItemis not. - A reserved word such as
int,class,new,public, orreturncannot be a name. - Names are case sensitive:
totalandTotalare two different variables. - By convention names for variables use camelCase:
unitPrice, notUnitPriceorunit_price. - The same name cannot be declared twice in the same block of code.
A variable of a primitive type holds the value itself. A variable of a reference type holds a reference, so it can also hold the special value null, meaning no object (Lesson 1.4 explains it).
A variable can change while the program runs, but it holds a single value at any moment. When a new value is stored, the old one is gone. The data type fixes what kind of value fits: an int variable cannot hold 3.5, and a boolean variable cannot hold 1.
Declare one variable of each type and print a receipt line for each.
String itemName = "Notebook";
int quantity = 3;
double unitPrice = 12.50;
boolean taxExempt = false;
double subtotal = quantity * unitPrice;
System.out.println("Item: " + itemName);
System.out.println("Quantity: " + quantity);
System.out.println("Unit price: " + unitPrice);
System.out.println("Subtotal: " + subtotal);
System.out.println("Tax exempt: " + taxExempt);
Item: Notebook Quantity: 3 Unit price: 12.5 Subtotal: 37.5 Tax exempt: false
Notice that 12.50 printed as 12.5. The trailing zero in the literal is formatting, not part of the value: a double stores a number, never a number of decimal places.
For each quantity, choose the most appropriate type and write the declaration.
| Quantity | Type | Declaration | Why |
|---|---|---|---|
| number of students in a class | int | int students = 24; | counted in whole units |
| the average of three test scores | double | double average = 87.5; | an average can have a fractional part |
| whether a door is locked | boolean | boolean locked = true; | exactly two possibilities |
| a person's name | String | String name = "Maya"; | text, so a reference type |
| the number of miles driven, to the tenth | double | double miles = 12.4; | a measurement with a fractional part |
The rule is: counted values are int; measured values are double; yes or no values are boolean; text is String.
Each line below breaks a rule, and the compiler rejects the program at that line.
public class Main {
public static void main(String[] args) {
int wholeNumber = 3.5;
}
}
Main.java:3: error: incompatible types: possible lossy conversion from double to int
int wholeNumber = 3.5;
^
1 error
A double value would lose its fractional part if it were forced into an int, so Java refuses to do it silently. A similar refusal happens for boolean flag = "yes"; (a String is not a boolean) and for int 2ndPlace = 2; (a name cannot start with a digit).
The exam asks you to pick the most appropriate data type for a given specification, so practice the counted, measured, yes or no, and text rule until it is automatic. It will also show code with a mismatch (a double assigned to an int, a String assigned to a boolean) and ask why it will not compile. Only int, double, and boolean are tested among primitive types; long, short, byte, float, and char are outside the course and the exam.
- Which type is most appropriate for the number of tickets sold in a day?
Show answer
int. A count of tickets is a whole number, and no fractional ticket exists. - Which type is most appropriate for a student's grade point average such as 3.67?
Show answer
double. It is a real number with a fractional part. - Which declaration compiles?
A. int score = 9.5; B. double score = 9; C. boolean score = 1; D. String score = 9;
Show answer
B. A whole number is accepted where a
doubleis expected (theint9 becomes 9.0), so B compiles. A would lose the fractional part, C stores anintin aboolean, and D stores a number where aStringobject is required. - What is printed?
int a = 7; double b = 7.0; System.out.println(a); System.out.println(b);
Show answer
7on one line and7.0on the next. The two variables hold values of different types, and adoublealways prints with a decimal point. - What is wrong with this program, and when does the problem show up?
int count = 1; int count = 2;
Show answer
The name
countis declared twice in the same block, so the compiler rejects the code. It is a syntax-level error found at compile time, before anything runs. - Which of these is a reference type:
int,boolean,String,double?Show answer
String. The other three are primitive types. A variable of typeStringholds a reference to a String object rather than the characters themselves.