A Java variable is a named storage location that holds one value of a fixed type: int for whole numbers, double for numbers with a decimal point and boolean for true or false. Each assignment replaces the value the variable held before, so you find what a variable holds by tracing the code one line at a time. System.out.print and System.out.println display values, and escape sequences such as \" and \n put special characters inside a string.
Quick check
Which of these values is a whole number: 12, 4.5 or true?Show answerHide answer
- The value 4.5 has a fractional part, and true is a truth value, not a number.
A box holds the number 5. You take the 5 out and put 9 in. What does the box hold now?Show answerHide answer
It holds 9. A new value replaces the old one, and a Java variable works the same way.
Know these already? Jump to the practice questions
What you'll be able to do
- Choose
int,doubleorbooleanfor a value, andfinalfor a value that must not change. - Determine what each variable holds after every line of a sequence of assignments.
- Predict the exact output of
printandprintln, including\",\\and\n. - Identify a line that fails to compile because it puts a
doublein anintor changes afinalvariable.
Key terms
Assignment statement
A statement such as x = 7; that evaluates the right side and stores the result in the variable on the left, replacing its old value.
- In plain English
- Work out the right side, then put the answer in the box on the left.
- Don't write
- "After
x = y;the namesxandyare the same variable."
Constant
A variable declared final, so it can be assigned only once. By convention its name is in capitals, such as MAX_SCORE.
- In plain English
- A value that is locked once it is set.
- Don't write
- "A
finalvariable can be given a new value later."
Escape sequence
A backslash and the character after it inside a string literal, standing for one special character.
- In plain English
- A two-character code for a character you can't type straight into a string.
- Don't write
- "
\nprints a backslash and the letter n."
How do you declare and initialize a variable?
A declaration gives a variable a type and a name, as in int score;. To initialize a variable is to give it its first value, often in the same statement: int score = 0;. Java's three primitive types in this course store their values directly:
| Type | Holds | Example |
|---|---|---|
int | whole numbers | int lives = 3; |
double | numbers with a decimal point | double price = 2.75; |
boolean | true or false | boolean done = false; |
A variable declared inside a method has no value until you assign one, and using it before then is a compile-time error. Names are case-sensitive, so score and Score are different variables, and a name cannot start with a digit.
Check yourself
Show answerHide answer
int 2ndPlace = 5; does not compile, because a variable name cannot start with a digit.
What does a variable hold after each assignment?
An assignment works right to left. Java evaluates the right side using the values the variables hold at that moment, then stores the result in the variable on the left. The old value is gone.
int x = 5;
int y = x;
x = x + 2;
y = y * 3;
| After line | x | y |
|---|---|---|
| 1 | 5 | none yet |
| 2 | 5 | 5 |
| 3 | 7 | 5 |
| 4 | 7 | 15 |
Line 2 copies the value 5 into y. The variables are not linked, so when line 3 changes x, y stays 5. Line 3 reads x as 5, adds 2 and stores 7 back in x: x = x + 2 is an instruction, not an equation.
Key idea
Trace one line at a time: work out the right side with the current values, then overwrite the variable on the left.
Check yourself
Show answerHide answer
b holds 2. Line 2 copied the value 2 into b, and changing a afterwards does not change b.
How do you choose a type, and what does final do?
Use int for a count or anything that cannot have a fraction, double for an amount that can, such as a price or an average, and boolean for a yes-or-no fact.
Java converts an int to a double automatically, so double d = 5; stores 5.0. It does not convert a double to an int in a plain assignment: int n = 2.5; is a compile-time error, because the fraction would be lost. Forcing that conversion with a cast is in the note on casting and the range of int.
Declaring a variable final makes it a constant: any assignment after the first is a compile-time error.
final int MAX_PLAYERS = 4;
MAX_PLAYERS = 5; // compile-time error
Use one for any value that must not change while the program runs.
Check yourself
Show answerHide answer
double, because an average can have a fractional part, such as 82.5.
How do print, println and escape sequences work?
System.out.println(value) prints the value and then ends the line; System.out.print(value) prints it and stays on the same line (Learn this).
A string literal is text between double quotes, such as "Hello"; the quotes are not printed. A double prints with a decimal point, so double d = 5; then System.out.println(d); prints 5.0, and a boolean prints as true or false.
Some characters can't go straight into a string literal, so you write an escape sequence:
| Inside the literal | Prints |
|---|---|
\" | a double quote |
\\ | one backslash |
\n | a line break |
So System.out.println("Say \"hi\"\nnow"); prints Say "hi" on one line and now on the next.
Check yourself
Show answerHide answer
A backslash followed by a double quote, \". Without the backslash, the quote would end the literal.
Worked example 1: Trace a sequence of assignments
Question: What is printed when this code segment runs?
int a = 4;
int b = a + 3;
a = b * 2;
double c = a;
b = b - a;
System.out.println(a);
System.out.println(b);
System.out.println(c);
What tells you the method
Several assignments change the same variables, so trace them with a table, one row per line.
Step 1: Trace each assignment.
Line abc1 4 2 4 7 3 14 7 4 14 7 14.0 5 14 -7 14.0 WhyEach right side uses the values in the row above, so line 5 subtracts the new
a, 14, not the old 4.Step 2: Print the final values in order.
aprints 14,bprints -7 andcprints 14.0.Whycis adouble, so it prints with a decimal point even though it was given theintvalue 14.
Check it
Re-trace line 5 alone: b is 7 and a is 14 at that point, so b - a is −7.
Answer
14 then -7 then 14.0, one per line.
Worked example 2: Predict print, println and escape sequences
Question: What is printed when this code segment runs?
System.out.print("Total: ");
System.out.println(42);
System.out.println("Type \"yes\" to save");
System.out.print("Saved in C:\\notes\nDone");
What tells you the method
A mix of print, println and backslashes: decide where each line ends, then decode each escape sequence.
Step 1: Join the first two statements.
printstays on the line afterTotal:, soprintln(42)continues it:Total: 42, then the line ends.WhyOnly
printlnor\nends a line.Step 2: Decode the escape sequences.
Each
\"prints a quote, givingType "yes" to save. In the last literal,\\prints one backslash and\nstarts a new line, givingSaved in C:\notesand thenDone.WhyEach backslash pairs with the character straight after it.
Check it
Count the line breaks: one from each println and one from \n, so the output has four lines.
Answer
Total: 42 then Type "yes" to save then Saved in C:\notes then Done, one per line.
Worked example 3: Find the line that will not compile
Question: Which line causes a compile-time error?
1: final double RATE = 0.25;
2: int hours;
3: hours = 6;
4: double pay = hours;
5: pay = pay + hours * RATE;
6: int total = pay;
- A) Line 2
- B) Line 4
- C) Line 5
- D) Line 6
What tells you the method
A compile-error question: check each line for a type mismatch, a use before assignment or a second assignment to a final variable.
Step 1: Check the declarations.
Line 2 declares
hourswithout a value, but line 3 assigns 6 before anything uses it.WhyA variable only needs a value before it is used.
Step 2: Check the conversions.
Line 4 stores an
intin adouble, which Java does automatically. Line 6 stores thedoublepayin anint, which the compiler rejects.WhyThat conversion could lose a fraction, so Java requires a cast for it.
Step 3: Check line 5.
It reads
RATEbut never assigns to it, sofinalis not broken;paybecomes 7.5.WhyOnly a second assignment to a constant is an error.
Check it
With line 6 deleted, the other five lines all compile, so line 6 is the only error.
Answer
D
Your turn
Question: What is printed when this code segment runs?
int x = 10;
int y = x;
x = x + 5;
double z = y;
System.out.print(x);
System.out.print(" ");
System.out.println(z);
Step 1: Trace the first three lines.
ygets a copy of 10, thenxbecomes 15, andystays 10.Step 2: Your go: work out
zand the single line that is printed.
Show the full solutionHide the solution
Step 2. z is a double holding the value of y, so it is 10.0. The two print calls put 15 and a space on the line, and println(z) adds 10.0 and ends the line.
Answer: 15 10.0
Traps
Trap
A double that holds a whole number prints without a decimal point.
It seems right because 5 and 5.0 are equal in math. But a double prints with a decimal point, so a double holding 5 prints 5.0.
After double d = 12; what does System.out.println(d); print?
12.0, because d is a double.
Trap
A single backslash in a string literal prints as it is written.
It seems right because a backslash looks like ordinary text. But a backslash starts an escape sequence, so the literal "C:\notes" prints C: and then otes on a new line. To print one backslash, write \\.
How many backslashes do you type in a string literal to print one backslash?
Two. The escape sequence \\ prints a single backslash.
What's examined
On the AP® Computer Science A exam, this Unit 1 skill sits inside other questions: multiple-choice questions ask what code prints, and in free response you declare variables in the Java you write. Output must be exact: 14 and 14.0 differ.
Practice questions
- Recall A program needs to record whether a library book is overdue. Which type fits the variable best?
- A)
int - B)
double - C)
boolean - D)
String
Show answer
Answer: C. Overdue or not is a yes-or-no fact, and boolean holds exactly true or false.
Why the others are wrong:
- A uses a number as a flag, so values such as 7 would be allowed and the meaning is hidden.
- B allows fractions, which mean nothing for a yes-or-no fact.
- D stores text such as "yes", which can be misspelled, and it is not a primitive type.
- Apply What is printed when this code segment runs?
int n = 3;
double d = n;
n = n * 4;
d = d + n;
System.out.println(n);
System.out.println(d);
Show answer
Answer: 12 then 15.0, one per line.
Marking points:
dstarts as a copy of 3, stored as 3.0.nbecomes 12, sodbecomes 3.0 + 12 = 15.0.dis adouble, so it prints with a decimal point.
- Apply What is printed when this code segment runs?
System.out.print("A\\B");
System.out.println("\"C\"");
System.out.print("D\nE");
Show answer
Answer: A\B"C" then D then E, one per line.
Marking points:
\\prints one backslash, andprintstays on the line.- Each
\"prints a quote, andprintlnthen ends the first line. \nputs E on the line after D.
- Exam-style Which code segment prints exactly the two lines below?
Hi
there
- A)
System.out.println("Hi"); System.out.print("there"); - B)
System.out.print("Hi"); System.out.print("there"); - C)
System.out.print("Hi\\nthere"); - D)
System.out.println("Hi" + "there");
Show answer
Answer: A. println ends the line after Hi, so there starts on the next line.
Why the others are wrong:
- B uses
printtwice, so it prints Hithere on one line. - C escapes the backslash, so it prints a backslash and the letter n instead of a line break.
- D joins the two strings before printing, so it prints Hithere.
- Exam-style This code segment is meant to swap the values of
aandb, so thataends up holding 9 andbholding 5. Give the number of the line that stops it working.
1: int a = 5;
2: int b = 9;
3: int temp = a;
4: a = b;
5: b = a;
Show answer
Answer: Line 5.
Marking points:
- After line 4,
ais 9 and the old 5 survives only intemp. - Line 5 copies 9 into
b, so both variables end up holding 9. - Changing line 5 to
b = temp;makesbhold 5, as intended.
- Exam-style Which statement can follow
final int LIMIT = 50;without causing a compile-time error?
- A)
LIMIT = 60; - B)
int spare = LIMIT - 8; - C)
LIMIT = LIMIT + 1; - D)
boolean big = LIMIT;
Show answer
Answer: B. It only reads LIMIT, and stores 42 in a new int variable.
Why the others are wrong:
- A assigns to a
finalvariable a second time. - C also assigns to
LIMITagain, even though it uses the old value. - D stores an
intin aboolean, and the types don't match.
- Recall Name the Java keyword that makes a variable a constant.
Show answer
Answer: final
Marking points:
- A
finalvariable can be assigned only once; a second assignment is a compile-time error.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
intstores whole numbers,doublestores numbers with a decimal point andbooleanstores onlytrueorfalse.- An assignment evaluates its right side with the current values, then overwrites the variable on the left; copying a value never links two variables.
- An
intvalue can go into adoubleand gains a decimal point; adoublevalue cannot go into anintwithout a cast. - A
finalvariable can be assigned only once. printlnends the line andprintdoes not;\",\\and\ngive a quote, a backslash and a line break.