1.4.1 The Assignment Operator
In Topic 1.2 you declared variables: int tickets; sets aside a storage location named tickets that can hold one int. But a declaration only creates the box. It does not put anything in it, and a program that tracks tickets, scores, or prices needs to store values there and change them as things happen. A movie theater’s program must record that you bought 3 tickets, then record 8 when your friends join.
The tool for that is a statement that says “put this value into that variable.” An assignment statement stores a value in a variable. It uses the assignment operator, the single equals sign =. The variable goes on the left, the value goes on the right, and the statement ends with a semicolon:
tickets = 3;
Read it as “tickets gets 3” or “store 3 in tickets,” not as “tickets equals 3.” That wording matters. In math, = states a fact that is always true. In Java, = is an action that happens once, at the moment that line runs.
The first time a variable is assigned a value, the variable is initialized. You can initialize a variable on a later line, as above, or in the declaration itself, as in int lives = 3;. Any assignment after that changes the value: the new value replaces the old one, and the old one is gone. A variable holds exactly one value at a time.
Key idea
The assignment operator = stores the value on its right in the variable on its left. The first assignment initializes the variable; each later assignment replaces the value it held.
Worked example: Initializing, then changing
Watch what tickets holds after each line.
int tickets;
tickets = 3;
System.out.println(tickets);
tickets = 8;
System.out.println(tickets);| Line | What happens | tickets holds |
Printed |
|---|---|---|---|
| 1 | Declared; no value yet | (nothing) | |
| 2 | Initialized: 3 is stored | 3 |
|
| 3 | The current value is printed | 3 |
3 |
| 4 | Changed: 8 replaces 3, and 3 is gone for good | 8 |
|
| 5 | The current value is printed | 8 |
8 |
3
8Line 3 and line 5 are the same statement, yet they print different things, because each one prints whatever tickets holds at the moment that line runs.
Now change one thing: initialize the variable in its declaration instead of on its own line.
int lives = 3;
System.out.println(lives);
lives = 2;
System.out.println(lives);3
2
Line 1 declares lives and initializes it to 3 in one statement. Line 3 is an ordinary assignment with no type in front, because lives already exists. Writing the type only belongs in the declaration; the type tells Java to create a new variable, and you create each variable once.
Watch out
Writing the assignment backward. Because = looks like the equals sign from math, where x = 10 and 10 = x mean the same thing, students sometimes put the value on the left:
int score = 0;
10 = score;This does not compile. Java reports:
error: unexpected type
required: variable
found: valueThe left side of = must be a variable, because it names the place where the value will be stored. 10 is a value, not a storage location, so there is nowhere to put anything. (The exact wording can vary between Java versions.) The fix is to put the variable on the left: score = 10;.
Pause and try
Question 1 · Multiple choice
What does this code print?
int laps = 2;
laps = 6;
laps = 4;
System.out.println(laps);24612
Check your reasoning
B. Each assignment replaces the value before it. laps is initialized to 2, then 6 replaces 2, then 4 replaces 6, so line 4 prints 4.
- A is wrong: 2 was only the starting value. Initializing a variable does not lock it.
- C is wrong: 6 was replaced by the last assignment. A variable remembers only its most recent value.
- D is wrong: assignment never adds values together. 2 + 6 + 4 = 12 treats
=as if it accumulated values.
Reread 1.4.1 The Assignment Operator if you chose differently.
Question 2 · Debugging
This code should store 100 in highScore and print it, but it does not compile. Explain the error and write the corrected line.
int highScore = 0;
100 = highScore;
System.out.println(highScore);Check your reasoning
Corrected line 2: highScore = 100;
The left side of = must be the variable that receives the value. Line 2 has the value 100 on the left, which is not a storage location, so the compiler reports unexpected type (it needed a variable and found a value). With the variable on the left, the code compiles and prints 100.
Reread 1.4.1 The Assignment Operator if you missed the error.
1.4.2 The Right Side Is Evaluated First
So far the right side of every assignment has been a single number. But programs usually need to compute the new value, often from the variable’s own current value. A game adds 5 points to a score; a store multiplies a price by a quantity. In Topic 1.3 you wrote arithmetic expressions such as 4 * 3 and printed their results. Now you can store those results.
An expression is any piece of code that produces a value: a literal such as 5, a variable such as points, or a combination of them with operators, such as points + 5. When an expression is evaluated, it produces one single value. That is exactly what an assignment needs.
Java carries out every assignment in two steps, always in this order:
- Evaluate the whole expression on the right, using the values the variables hold right now, to get one value.
- Store that value in the variable on the left.
Because the right side is finished before anything is stored, a variable can appear on both sides. The right side uses the old value, and only then does the new value replace it.
Key idea
Java evaluates the entire right side to one value first, using the current values of any variables in it, and only then stores that value in the variable on the left.
Worked example: Using a variable's own value
int points = 10;
points = points + 5;
System.out.println(points);Line 2 looks impossible as math (no number equals itself plus 5), but as an action it is ordinary. Here are the two steps:
| Step | Work | points holds |
|---|---|---|
| Before line 2 | 10 |
|
| Evaluate right side | points + 5 → 10 + 5 → 15 |
10 (still) |
| Store on the left | 15 replaces 10 |
15 |
15During the evaluate step, points still holds 10. It changes only in the store step.
Now vary the right side so it is a different variable. When the expression is just a variable, its value is copied into the variable on the left. After that, the two variables are separate boxes that happen to hold the same number.
int monday = 12;
int tuesday = monday;
monday = 20;
System.out.println(monday);
System.out.println(tuesday);| Line | Work | monday |
tuesday |
|---|---|---|---|
| 1 | Store 12 | 12 |
|
| 2 | Evaluate monday → 12; store it |
12 |
12 |
| 3 | Store 20 in monday |
20 |
12 |
20
12
Line 3 changes only monday. Line 2 copied the value 12 into tuesday; it did not link the two variables, so tuesday keeps 12.
Watch out
Expecting an assignment to update itself later. In a spreadsheet, a cell that holds a formula updates whenever the cells it uses change. Java assignments do not work that way, and students who expect them to are surprised by code like this:
int price = 4;
int quantity = 3;
int total = price * quantity;
quantity = 5;
System.out.println(total);12You might expect 20, since 4 × 5 is 20. But line 3 ran once, when quantity was 3, and stored the single value 12. total holds a number, not a formula. Changing quantity on line 4 does nothing to total. Java gives no error here, because nothing is illegal: this is a logic error (Topic 1.1), where the program runs but gives the wrong answer.
The fix is to run the assignment again after the change:
int price = 4;
int quantity = 3;
int total = price * quantity;
quantity = 5;
total = price * quantity;
System.out.println(total);20Pause and try
Question 3 · Tracing
Write the exact output. Use a trace table with columns for home and away.
int home = 5;
int away = home;
home = home + 3;
away = away * 2;
System.out.println(home);
System.out.println(away);Check your reasoning
8
10| Line | Work | home |
away |
|---|---|---|---|
| 1 | Store 5 | 5 |
|
| 2 | Copy the value of home |
5 |
5 |
| 3 | home + 3 → 5 + 3 → 8; store it |
8 |
5 |
| 4 | away * 2 → 5 * 2 → 10; store it |
8 |
10 |
Line 2 copied 5 into away, so line 3 does not affect away. Line 4 doubles away’s own value, which is still 5.
Reread 1.4.2 The Right Side Is Evaluated First if your output differed.
Question 4 · Multiple choice
What does this code print?
int width = 4;
int area = width * 3;
width = 10;
System.out.println(area);123010- Nothing; it does not compile
Check your reasoning
A. Line 2 evaluates width * 3 once, when width is 4, and stores 12 in area. Changing width on line 3 does not rerun line 2.
- B is wrong: 30 is 10 × 3, which assumes
arearecomputes itself whenwidthchanges, like a spreadsheet formula. It does not. - C is wrong: 10 is the new value of
width. Line 4 printsarea, a separate variable. - D is wrong: every statement is legal. Assigning a new value to
widthafter using it is allowed.
Reread 1.4.2 The Right Side Is Evaluated First if you chose differently.
1.4.3 Every Expression Has a Type
Every variable has a type, chosen when it is declared. Every value has a type too. So when an assignment stores the value of an expression, Java has to know: is that value an int, a double, or a boolean? And does it fit the variable?
The answer is that the value of an expression has a type, and that type comes from how the expression is evaluated. You already know the rules from Topic 1.3. An operation on two int values produces an int; an operation with at least one double produces a double. Java applies those rules one operation at a time, following the order of operations, and the type of the last operation’s result is the type of the whole expression.
The value you store must come from a compatible type: one the variable’s type accepts. An int variable accepts int values, a double variable accepts double values, and a boolean variable accepts true or false. (Topic 1.5 shows a few cases where Java converts a value from one type to another for you.) Why is Java strict about this? Because a variable’s type decides how much memory it uses and what it can hold. An int variable has no place to keep the .33 of 84.33, so Java will not silently throw it away.
Key idea
Evaluating an expression produces one value, and that value has a type determined by the operations that produced it. You can store it only in a variable whose type is compatible.
Worked example: Averaging quiz scores
Three quiz scores are 85, 90, and 78. Look at the type of each right side.
int total = 85 + 90 + 78;
double average = total / 3.0;
int roughAverage = total / 3;
System.out.println(total);
System.out.println(average);
System.out.println(roughAverage);| Line | Evaluate the right side | Type | Stored |
|---|---|---|---|
| 1 | 85 + 90 → 175, then 175 + 78 → 253 |
int |
253 |
| 2 | total / 3.0 → 253 / 3.0: one double, so a double |
double |
84.33333333333333 |
| 3 | total / 3 → 253 / 3: two ints, so integer division |
int |
84 |
253
84.33333333333333
84Line 2 divides by 3.0, a double, so the result is a double and fits in the double variable average. Line 3 divides two int values, so the result is the int 84 (the decimal part is dropped, as in Topic 1.3), which fits in the int variable roughAverage. In both lines the type of the expression matches the type of the variable.
The type comes from the operations, not from how the answer looks. 10 / 4 * 2.0 ends up as 4.0, a double, even though 4 is a whole number: 10 / 4 is the int 2, and then 2 * 2.0 involves a double, so the result is the double 4.0.
Watch out
Storing a double result in an int variable. Students often declare a variable as int out of habit, then divide by a double:
int total = 253;
int average = total / 3.0;The right side, 253 / 3.0, is a double, but average is an int. This does not compile. Java reports something like:
error: incompatible types: possible lossy conversion from double to int“Lossy” means the decimal part would be lost. The compiler refuses because it cannot know whether you meant to lose it. The fix is to declare the variable with a type that matches the value: double average = total / 3.0;. The same error family appears for other mismatches; for example, int count = true; gives incompatible types: boolean cannot be converted to int.
Pause and try
Question 5 · Multiple choice
What are the type and the value of the expression 9 / 2 + 0.5?
doublevalue5.0doublevalue4.5intvalue4intvalue5
Check your reasoning
B. Division comes before addition. 9 / 2 uses two int values, so it is the int 4. Then 4 + 0.5 involves a double, so the result is the double 4.5. Storing it with double value = 9 / 2 + 0.5; and printing value displays 4.5.
- A is wrong: 5.0 comes from computing
9 / 2as 4.5. With twointvalues, the decimal part is dropped first. - C is wrong: the last operation adds a
double, so the whole expression is adouble, not anint. - D is wrong: it is neither the right type nor the right value. Nothing in the expression rounds 4.5 up.
Reread 1.4.3 Every Expression Has a Type if you chose differently.
Question 6 · Debugging
This code should store half of 9 and print 4.5, but it does not compile. Explain why and write the corrected line.
int half = 9 / 2.0;
System.out.println(half);Check your reasoning
Corrected line 1: double half = 9 / 2.0;
The expression 9 / 2.0 includes a double, so its value is the double 4.5. The variable half is an int, and an int cannot hold the .5, so the compiler reports incompatible types: possible lossy conversion from double to int. Declaring half as a double makes the types compatible, and the code prints 4.5.
Changing the expression to 9 / 2 would compile, but it would store the int 4, not 4.5, so it does not do what the code is meant to do.
Reread 1.4.3 Every Expression Has a Type if you missed the error.
1.4.4 Assign Before You Use
A declaration creates a variable with no value in it. What should happen if a program tries to use that variable before anything has been stored there? Back in 1.4.1, the trace table showed (nothing) for a variable that was only declared. An expression cannot compute 50 + nothing.
Java’s rule: every variable must be assigned a value before it is used in an expression. The compiler checks this before the program ever runs. It looks at each place a variable is used and asks: on every path to this line, has the variable already been assigned? If not, it refuses to compile.
Why not just use 0? Because 0 might be wrong. A bonus of 0, a price of 0, a temperature of 0: each is a real value that would quietly produce a believable but wrong answer, a logic error that is hard to find. A compile error forces you to decide what the starting value should be.
Key idea
Worked example: Declared now, initialized later
int steps;
steps = 4000;
int goal = steps + 1000;
System.out.println(goal);| Line | What happens | steps |
goal |
|---|---|---|---|
| 1 | steps is declared with no value |
(nothing) | |
| 2 | steps is initialized |
4000 |
|
| 3 | steps + 1000 → 4000 + 1000 → 5000 |
4000 |
5000 |
5000This compiles because steps is initialized on line 2, before line 3 uses it. Declaring and initializing on separate lines is allowed; the order is what matters.
Now remove the assignment and see what changes:
int bonus;
int total = 50 + bonus;
System.out.println(total);This does not compile. Java reports something like:
error: variable bonus might not have been initialized
Line 2 uses bonus in the expression 50 + bonus, but no line before it ever stored a value in bonus. The fix is to initialize it first, for example int bonus = 0;, if 0 really is the bonus you mean.
Watch out
Thinking a declaration gives a default value. Students who have seen other languages, or who picture an empty box as “zero,” expect int bonus; to hold 0. It holds nothing usable, and the compiler says so with might not have been initialized. The error points to the line where the variable is used, not where it was declared, so look upward from that line for the missing assignment.
Pause and try
Question 7 · Multiple choice
Which code segment does not compile?
int a;thena = 3;thenint b = a + 1;int e;thenint f = e + 2;int c = 0;thenc = c + 1;int d;thend = 5;
Check your reasoning
B. e is declared but never assigned before e + 2 uses it, so the compiler reports variable e might not have been initialized.
- A compiles:
ais initialized on its second line, beforea + 1uses it. - C compiles:
cis initialized to 0 in its declaration, soc + 1can use it. (It becomes 1.) - D compiles:
dis declared and then assigned. It is never used in an expression, and assigning to a variable is not “using” it.
Reread 1.4.4 Assign Before You Use if you chose differently.
Question 8 · Short answer
Java could have been designed to give every declared variable a starting value of 0 automatically. Explain why refusing to compile is more helpful to a programmer who forgot to initialize a variable.
Check your reasoning
Model answer: If Java quietly used 0, the program would run and print an answer that looks reasonable but is wrong, because 0 was never the value the programmer intended. That is a logic error, which can go unnoticed. A compile error stops the program before it runs and points to the exact line, so the programmer must choose the correct starting value.
A complete answer must say that:
- a silent default could produce wrong results without any error message, and
- the compile error catches the mistake early and forces a deliberate choice.
Reread 1.4.4 Assign Before You Use if your answer differed.
1.4.5 Reference Variables and null
Everything so far has used primitive types: int, double, and boolean. Recall from Topic 1.2 that any other type is a reference type, and that reference types are used for objects, bundles of related information such as a piece of text. String, the type for text such as "Ada", is a reference type. A variable of a reference type does not hold a number or true/false. It is connected to an object. Topics 1.12 and 1.13 explain objects and that connection in detail. For this chapter, two facts are enough: a reference variable can be assigned an object (you have already seen string literals, and in 1.4.6 you will create a new object for reading input), or it can be assigned the special value null.
Why would you need a special value? Sometimes a program needs a reference variable before it has anything to connect it to. A sign-up form asks for a nickname, but a player may not have one yet. The program must still initialize the variable (1.4.4), and it should say clearly “no nickname yet” rather than invent one.
The literal null is a special value meaning that a reference variable is not connected to any object. Like 3 or true, it is a literal: a fixed value written directly in the code. It is not text, so it has no double quotes.
Key idea
A reference variable can be assigned an object or null. The literal null means the variable is not associated with any object.
Worked example: A nickname that arrives later
String nickname = null;
System.out.println(nickname);
nickname = "Ace";
System.out.println(nickname);| Line | What happens | nickname holds |
Printed |
|---|---|---|---|
| 1 | Initialized to null: no object yet |
null |
|
| 2 | println displays the value null |
null |
null |
| 3 | Assigned the string "Ace", replacing null |
connected to "Ace" |
|
| 4 | println displays the text |
connected to "Ace" |
Ace |
null
AceLine 1 counts as initialization, so line 2 compiles. Printing a variable that holds null displays the word null. Line 3 is an ordinary assignment: the new value replaces the old one, just as with an int.
Now vary the type. null belongs only to reference types. A primitive variable always holds an actual number or true/false, so “no object” makes no sense for it:
int age = null;This does not compile. Java reports something like:
error: incompatible types: <null> cannot be converted to int
This is the compatible-type rule from 1.4.3 again: null is not a value an int can hold. If you need “no age entered yet” for an int, pick a real starting value, such as 0, and be clear about what it means.
Watch out
Confusing null with "null". String nickname = null; and String nickname = "null"; both print null, but they are different. The first has no quotes: the variable is connected to no object. The second has quotes: it is a string literal made of the four letters n, u, l, l, a real piece of text that just happens to spell that word. Students mix them up because the printed output looks identical. Write null without quotes when you mean “no object.”
Pause and try
Question 9 · Tracing
Write the exact output.
String team = null;
System.out.println(team);
team = "Hawks";
System.out.println(team);
team = null;
System.out.println(team);Check your reasoning
null
Hawks
null| Line | team holds |
Printed |
|---|---|---|
| 1 | null |
|
| 2 | null |
null |
| 3 | connected to "Hawks" |
|
| 4 | connected to "Hawks" |
Hawks |
| 5 | null |
|
| 6 | null |
null |
Line 5 shows that null can also replace an object. Assignment always replaces the old value, whatever kind it is.
Reread 1.4.5 Reference Variables and null if your output differed.
Question 10 · Multiple choice
Which declaration compiles?
int score = null;double price = null;String city = null;boolean done = null;
Check your reasoning
C. null means “not connected to any object,” so it can be stored only in a variable of a reference type. String is a reference type.
- A is wrong:
intis primitive. Java reportsincompatible types: <null> cannot be converted to int. - B is wrong:
doubleis primitive too, so it gets the same error, ending into double. - D is wrong:
booleanis primitive and can hold onlytrueorfalse. The error ends into boolean.
Reread 1.4.5 Reference Variables and null if you chose differently.
1.4.6 Input and the Scanner Class
Every program so far has had its values written into the code. The quiz scores, the ticket counts, the nickname: to change any of them, you would have to edit the program and run it again. Real programs take in information while they run. Input is data a program receives from outside itself.
Input comes in many forms:
| Form | What the program receives | Everyday example |
|---|---|---|
| Tactile | Touches, presses, or movements | Tapping a phone screen, a game button |
| Audio | Sound | Speaking to a voice assistant |
| Visual | Images or video | A camera scanning a QR code |
| Text | Characters | Typing your age into a form |
This course works with text input. In Java, one way to get text that the user types on the keyboard is the Scanner class: a ready-made part of Java whose job is reading text and turning it into values your program can store. (Exactly what kind of input a particular program accepts is up to its designer, and the AP exam does not test any particular one; you will use Scanner in class programs and again in Topics 1.13 and 1.14.)
Here is a complete program that asks for the user’s age and stores it:
import java.util.Scanner;
public class AgeFromKeyboard
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("How old are you? ");
int age = input.nextInt();
System.out.print("Age: ");
System.out.println(age);
}
}
Take it apart one new piece at a time:
| Code | What it does |
|---|---|
import java.util.Scanner; |
Placed at the very top, before the class. Tells Java where to find Scanner, which is not automatically available to every program. |
Scanner input |
Declares a variable named input of type Scanner, a reference type. |
= new Scanner(System.in); |
Creates a new Scanner object and assigns it to input. System.in stands for the keyboard. |
int age = input.nextInt(); |
Waits for the user to type a whole number and press Enter, then stores that number in age. |
Two pieces use ideas taught later. new Scanner(System.in) creates an object, which Topic 1.13 explains fully; for now, use this line as a pattern whenever you need keyboard input. input.nextInt() asks the Scanner named input for its next whole number; Topic 1.14 explains this kind of call, so for now read it as “ask input for the next whole number.” Notice that int age = input.nextInt(); is still an ordinary assignment from 1.4.2: the right side produces one int value, and it is stored in age.
A program that waits for typing gives different output every time it runs, depending on what someone types. To make examples you can trace exactly, this guide gives the Scanner its input as a string instead of the keyboard: new Scanner("16") reads from the text 16 exactly as if a user had typed it. Everything else, including nextInt(), works the same way.
Key idea
A Scanner reads text input. Import it with import java.util.Scanner; then create one with new Scanner(System.in) to read the keyboard, or with new Scanner and a string to read that text instead.
Worked example: Reading an age from text
import java.util.Scanner;
public class AgeFromText
{
public static void main(String[] args)
{
Scanner input = new Scanner("16");
int age = input.nextInt();
System.out.print("Age: ");
System.out.println(age);
}
}| Line | What happens | age |
|---|---|---|
| 1 | Makes Scanner available to this program |
|
| 7 | Creates a Scanner that reads the text 16; stores it in input |
|
| 8 | input.nextInt() reads 16 and produces the int 16; it is stored |
16 |
| 9–10 | Prints the label, then the value on the same line | 16 |
Age: 16Swap "16" for System.in on line 7 and the program behaves like AgeFromKeyboard above: it reads whatever number the user types instead.
Watch out
Forgetting the import. System needs no import, so students expect the same of Scanner:
public class NoImport
{
public static void main(String[] args)
{
Scanner input = new Scanner("16");
int age = input.nextInt();
System.out.println(age);
}
}This does not compile. Java does not know what Scanner is, and reports (once for each place the name appears on line 5):
error: cannot find symbol
symbol: class ScannerThe fix is to add import java.util.Scanner; as the first line of the file, before public class. Topic 1.7 explains where classes such as Scanner live and why some need an import.
Pause and try
Question 11 · Multiple choice
A phone app lets you unlock it by looking at the camera, by saying a passphrase, by pressing your thumb on a sensor, or by typing a PIN. Which of these is the kind of input a Scanner reads?
- Looking at the camera
- Saying a passphrase
- Pressing your thumb on the sensor
- Typing a PIN
Check your reasoning
D. A Scanner reads text: characters such as the digits of a PIN.
- A is wrong: a camera image is visual input.
- B is wrong: a spoken passphrase is audio input.
- C is wrong: a thumb press is tactile input.
All four are input, because all four bring information into the program from outside. Only the typed PIN is text.
Reread 1.4.6 Input and the Scanner Class if you chose differently.
Question 12 · Short answer
This guide’s examples create a Scanner with new Scanner("16") instead of new Scanner(System.in). Explain what is different about where each one gets its input, and why the guide uses the string version for examples.
Check your reasoning
Model answer: new Scanner(System.in) reads whatever the user types on the keyboard while the program runs, so the input, and therefore the output, can change every run. new Scanner("16") reads from the fixed text 16, so the program reads the same input every time. The guide uses the string version so that every example has one exact output you can trace and check. The reading calls, such as nextInt(), work the same way with either one.
A complete answer must mention that:
System.inis the keyboard and a string is fixed text, and- fixed text makes the output predictable, while the reading works the same either way.
Reread 1.4.6 Input and the Scanner Class if your answer differed.
1.4.7 Reading Values with a Scanner
Most programs need more than one input, and not all of them are whole numbers. An order form needs a customer’s name (text), a quantity (a whole number), and a price (a decimal). A Scanner has a different reading call for each type, and each call produces one value you can assign to a variable of that type.
Picture the input as a line of text with a marker showing where the Scanner will read next. Every read takes the next piece from the marker onward, and the marker moves past it. Pieces are separated by spaces or line breaks.
| Call | Reads | Produces a |
|---|---|---|
nextInt() |
The next piece, as a whole number | int |
nextDouble() |
The next piece, as a number that may have a decimal point | double |
nextLine() |
Everything up to the end of the current line, spaces included | String |
nextInt() and nextDouble() skip over any spaces or line breaks before their piece. nextLine() returns the rest of the line without the line break itself, and moves the marker to the start of the next line.
Key idea
Each reading call takes the next piece of input and produces one value of its type. Calls read in order, and each result is stored with an ordinary assignment.
Worked example: Reading an order
The input text has a name on the first line and two numbers on the second. In a string literal, \n is a line break (Topic 1.3), so this is the same as a user typing Ada Lovelace, pressing Enter, then typing 3 2.5.
import java.util.Scanner;
public class OrderReader
{
public static void main(String[] args)
{
Scanner input = new Scanner("Ada Lovelace\n3 2.5");
String customer = input.nextLine();
int quantity = input.nextInt();
double price = input.nextDouble();
double cost = quantity * price;
System.out.println(customer);
System.out.print("Cost: ");
System.out.println(cost);
}
}The ▸ shows where input will read next.
| Line | Call / work | Value stored | Input left after the line |
|---|---|---|---|
| 7 | (Scanner created) | ▸Ada Lovelace / 3 2.5 |
|
| 8 | input.nextLine() |
customer ← "Ada Lovelace" |
▸3 2.5 |
| 9 | input.nextInt() |
quantity ← 3 |
▸ 2.5 |
| 10 | input.nextDouble() |
price ← 2.5 |
(nothing left) |
| 11 | 3 * 2.5 → 7.5 |
cost ← 7.5 |
Ada Lovelace
Cost: 7.5Line 8 reads the whole first line, including the space between the two names, because nextLine stops only at the line break. Line 11 is the type rule from 1.4.3: an int times a double is a double, so cost must be a double.
Now change only the input text, spreading the numbers over extra lines and spaces:
import java.util.Scanner;
public class OrderReaderLines
{
public static void main(String[] args)
{
Scanner input = new Scanner("Ada Lovelace\n3\n\n 2.5");
String customer = input.nextLine();
int quantity = input.nextInt();
double price = input.nextDouble();
double cost = quantity * price;
System.out.println(customer);
System.out.print("Cost: ");
System.out.println(cost);
}
}Ada Lovelace
Cost: 7.5
The output is identical. nextInt() and nextDouble() skip the line breaks and spaces to find their pieces, so what matters is the order of the pieces, not how they are spaced. The order of the reading calls must match the order of the input.
Watch out
Input that does not match the call. nextInt() can only produce a whole number. If the next piece is something else, such as a word, the program crashes while it runs:
import java.util.Scanner;
public class WrongInput
{
public static void main(String[] args)
{
Scanner input = new Scanner("three 2.5");
System.out.println("Reading the quantity...");
int quantity = input.nextInt();
System.out.println(quantity);
}
}Reading the quantity...
Exception in thread "main" java.util.InputMismatchExceptionThe program compiles, because nothing in the code is wrong as Java syntax. The problem appears only at run time, on line 9, when the next piece turns out to be three. An InputMismatchException is the exception (Topic 1.1) a Scanner throws when the input does not match the type you asked for. Line 8 already ran, so its message appears before the crash; line 10 never runs. (The exception message also lists lines that show where it happened; their details vary between Java versions.) The fix is input that matches: with "3 2.5" the same program reads 3. When a real user types the input, they must type what the program asks for, which is why programs print a prompt such as How old are you? first.
Pause and try
Question 13 · Tracing
Write the exact output. Track what each variable holds.
import java.util.Scanner;
public class ReadsInOrder
{
public static void main(String[] args)
{
Scanner input = new Scanner("8 2.5 6");
int first = input.nextInt();
double second = input.nextDouble();
int third = input.nextInt();
int sum = first + third;
System.out.println(sum);
System.out.println(second);
}
}Check your reasoning
14
2.5| Line | Call / work | Value stored | Input left |
|---|---|---|---|
| 8 | input.nextInt() |
first ← 8 |
▸ 2.5 6 |
| 9 | input.nextDouble() |
second ← 2.5 |
▸ 6 |
| 10 | input.nextInt() |
third ← 6 |
(nothing) |
| 11 | 8 + 6 → 14 |
sum ← 14 |
The reads happen in order, so third gets the third piece, 6, not 2.5. sum adds first and third only.
Reread 1.4.7 Reading Values with a Scanner if your output differed.
Question 14 · Multiple choice
A Scanner is created with new Scanner("Blue Team\n7"). The first reading call is String team = input.nextLine();. What does team hold?
"Blue""Blue Team""Blue Team 7""7"
Check your reasoning
B. nextLine() reads everything up to the end of the current line, spaces included, and leaves out the line break. The first line is Blue Team. A following input.nextInt() would then read 7.
- A is wrong:
nextLine()does not stop at a space. Stopping at the space is how the number-reading calls separate pieces. - C is wrong:
nextLine()stops at the line break, so the 7 on the next line is not included. - D is wrong: reads happen in order from the start of the input, so the first call cannot skip to the 7.
Reread 1.4.7 Reading Values with a Scanner if you chose differently.
Putting it together
This program estimates the fuel cost of a trip. It reads the trip’s name, the distance in miles, the car’s miles per gallon, and the price of one gallon, then computes the cost.
import java.util.Scanner;
public class TripCost
{
public static void main(String[] args)
{
Scanner input = new Scanner("Beach day\n240 30\n3.5");
String tripName = input.nextLine();
int miles = input.nextInt();
int milesPerGallon = input.nextInt();
double pricePerGallon = input.nextDouble();
int gallons = miles / milesPerGallon;
double cost = gallons * pricePerGallon;
System.out.println(tripName);
System.out.print("Gallons: ");
System.out.println(gallons);
System.out.print("Cost: ");
System.out.println(cost);
miles = miles + 60;
System.out.print("Gallons still stored: ");
System.out.println(gallons);
}
}First, the reads (the ▸ marks where input will read next):
| Line | Call | Value stored | Input left after the line |
|---|---|---|---|
| 7 | (Scanner created) | ▸Beach day / 240 30 / 3.5 |
|
| 8 | input.nextLine() |
tripName ← "Beach day" |
▸240 30 / 3.5 |
| 9 | input.nextInt() |
miles ← 240 |
▸ 30 / 3.5 |
| 10 | input.nextInt() |
milesPerGallon ← 30 |
▸ / 3.5 |
| 11 | input.nextDouble() |
pricePerGallon ← 3.5 |
(nothing left) |
Then the computations. For each right side, evaluate first, check the type, then store:
| Line | Evaluate the right side | Type | Stored |
|---|---|---|---|
| 12 | 240 / 30 → 8 (two int values) |
int |
gallons ← 8 |
| 13 | 8 * 3.5 → 28.0 (one double) |
double |
cost ← 28.0 |
| 19 | miles + 60 → 240 + 60 → 300 |
int |
miles ← 300 |
Lines 14 to 18 print the name and the two results. Line 19 changes miles, but line 12 ran long before and stored the single value 8 in gallons, so lines 20 and 21 still print 8:
Beach day
Gallons: 8
Cost: 28.0
Gallons still stored: 8
Every idea from the chapter appears. The Scanner is a new object assigned to a reference variable and needs the import on line 1. Each reading call produces one value of its type, stored with an ordinary assignment, and the calls read in order. Each right side is evaluated to one value whose type must be compatible with its variable: cost must be a double because gallons * pricePerGallon is a double. Every variable is initialized before it is used. And an assignment stores a value, not a formula, so changing miles does not change gallons.
Common mistakes
The compiler messages from this chapter, collected for quick lookup. Wording can vary slightly between Java versions.
| Java says | Usual cause | Fix |
|---|---|---|
unexpected type (required: variable, found: value) |
Value on the left of =, as in 10 = score; |
Put the variable on the left: score = 10; |
incompatible types: possible lossy conversion from double to int |
A double expression stored in an int variable |
Declare the variable as double |
incompatible types: <null> cannot be converted to int |
null stored in a primitive variable |
Use null only with reference types like String |
variable ... might not have been initialized |
Variable used before any value was stored | Assign a value before the line that uses it |
cannot find symbol (symbol: class Scanner) |
Missing import | Add import java.util.Scanner; at the top |
InputMismatchException (while running) |
Input piece does not match the reading call | Read in the order the input appears; match the types |
Vocabulary
| Term | Definition | Example |
|---|---|---|
| assignment statement | A statement that stores a value in a variable | tickets = 8; |
| assignment operator | The = sign; stores the value on its right in the variable on its left |
lives = 2; |
| initialized | Describes a variable that has been assigned its first value | int lives = 3; |
| expression | Code that is evaluated to produce one value, which has a type | total / 3.0 (a double) |
| compatible | Describes a value whose type the variable’s type accepts | an int value for an int variable |
null |
A literal meaning a reference variable is not connected to any object | String nickname = null; |
| input | Data a program receives from outside itself: tactile, audio, visual, or text | a typed age |
Scanner |
A Java class that reads text input and turns it into values | new Scanner(System.in) |
| InputMismatchException | The exception thrown when input does not match the type a Scanner call asks for |
nextInt() reading three |
Chapter summary
- An assignment statement uses
=to store the value on its right in the variable on its left. The first assignment initializes the variable; later ones replace its value. - Java evaluates the whole right side to one value first, using the variables’ current values, then stores it. The variable holds that value, not a formula, so later changes to other variables do not update it.
- Every expression’s value has a type that comes from its operations. That value can be stored only in a variable of a compatible type, and a variable must be initialized before it is used in an expression.
- A reference variable, such as a
String, can be assigned an object ornull, which means “no object.” Primitive variables cannot holdnull. - Input can be tactile, audio, visual, or text. A
Scanner(imported fromjava.util) reads text, from the keyboard withSystem.inor from a string, and itsnextInt,nextDouble, andnextLinecalls read the input in order.
Review questions
Question 15 · Multiple choice
What does this code print?
double result = 11 / 4 * 2.0 + 1;
System.out.println(result);6.55.05- Nothing; it does not compile
Check your reasoning
B. / and * have the same precedence and come before +, and operators with the same precedence go left to right. 11 / 4 uses two int values, so it is the int 2. Then 2 * 2.0 involves a double, giving the double 4.0. Finally 4.0 + 1 is the double 5.0, which is stored in the double variable result.
- A is wrong: 6.5 treats
11 / 4as 2.75. With twointvalues the decimal part is dropped before the multiplication. - C is wrong: once
2.0enters the calculation, every later result is adouble, and adoubleprints with a decimal point. - D is wrong: a
doublevalue stored in adoublevariable is compatible.
Reread 1.4.3 Every Expression Has a Type if you chose differently.
Question 16 · Tracing
A student wants to swap the values of first and second, then add 1 to first. Write the exact output, and say whether the swap worked.
int first = 5;
int second = 9;
first = second;
second = first;
first = first + 1;
System.out.println(first);
System.out.println(second);Check your reasoning
10
9| Line | Work | first |
second |
|---|---|---|---|
| 1 | Store 5 | 5 |
|
| 2 | Store 9 | 5 |
9 |
| 3 | Copy second (9) into first |
9 |
9 |
| 4 | Copy first (now 9) into second |
9 |
9 |
| 5 | first + 1 → 9 + 1 → 10 |
10 |
9 |
The swap did not work. Line 3 replaced 5 with 9, and the 5 was gone for good, so line 4 had only 9 to copy. Each variable holds one value, and assignment replaces it. A swap needs a third variable to save one value first, such as int saved = first; before line 3, then second = saved; in place of line 4.
Reread 1.4.2 The Right Side Is Evaluated First and 1.4.1 The Assignment Operator if your output differed.
Question 17 · Multiple choice
Which declaration does not compile?
String coach = null;double rate = 7 / 2.0;int laps = 12 / 5;int total = 3.0 * 4;
Check your reasoning
D. 3.0 * 4 involves a double, so its value is the double 12.0. An int variable is not compatible with a double value, so Java reports possible lossy conversion from double to int, even though 12.0 has nothing after the decimal point. The compiler checks the type, not the particular value.
- A compiles:
Stringis a reference type, so it can holdnull. - B compiles:
7 / 2.0is thedouble3.5, stored in adouble. - C compiles:
12 / 5uses twointvalues, so it is theint2, stored in anint.
Reread 1.4.3 Every Expression Has a Type and 1.4.5 Reference Variables and null if you chose differently.
Question 18 · Short answer
Here are two versions of the same code. Version 1 does not compile. Version 2 prints null. Explain the difference.
Version 1:
String motto;
System.out.println(motto);Version 2:
String motto = null;
System.out.println(motto);Check your reasoning
Model answer: In version 1, motto is declared but never assigned, so it has not been initialized. Java requires a value before a variable is used, and reports variable motto might not have been initialized. In version 2, motto is initialized with the value null. That is a real value meaning “no object,” so the variable may be used, and printing it displays null.
A complete answer must say that:
- “never assigned” (no value) and “assigned
null” (a value meaning no object) are different, and - only an initialized variable can be used, which is why version 1 fails and version 2 runs.
Reread 1.4.4 Assign Before You Use and 1.4.5 Reference Variables and null if your answer differed.
Question 19 · Debugging
This program should read a quiz name and a score of 17 out of 20, start with no bonus points, and print the percentage 85.0. It has two compile errors. Find both, explain each, and write the corrected lines.
import java.util.Scanner;
public class QuizScores
{
public static void main(String[] args)
{
Scanner input = new Scanner("Unit 1 quiz\n17 20");
String quizName = input.nextLine();
int myScore = input.nextInt();
int maxPoints = input.nextInt();
int bonus = null;
int percent = (myScore + bonus) * 100.0 / maxPoints;
System.out.println(quizName);
System.out.println(percent);
}
}Check your reasoning
Error 1 (line 11): int bonus = null; tries to store null in an int. null means “no object” and fits only reference types, so Java reports incompatible types: <null> cannot be converted to int. “No bonus points” for a number is 0. Fix: int bonus = 0;.
Error 2 (line 12): the right side, (myScore + bonus) * 100.0 / maxPoints, involves 100.0, so its value is a double. It cannot be stored in the int variable percent: possible lossy conversion from double to int. Fix: double percent = (myScore + bonus) * 100.0 / maxPoints;.
With both fixes, line 12 evaluates (17 + 0) * 100.0 / 20 → 1700.0 / 20 → 85.0. Here is the corrected program (renamed so it can be saved alongside the original):
import java.util.Scanner;
public class QuizScoresFixed
{
public static void main(String[] args)
{
Scanner input = new Scanner("Unit 1 quiz\n17 20");
String quizName = input.nextLine();
int myScore = input.nextInt();
int maxPoints = input.nextInt();
int bonus = 0;
double percent = (myScore + bonus) * 100.0 / maxPoints;
System.out.println(quizName);
System.out.println(percent);
}
}Unit 1 quiz
85.0Reread 1.4.5 Reference Variables and null and 1.4.3 Every Expression Has a Type if you missed either error.
Question 20 · Tracing
Fourteen boxes are shared among four helpers. Write the exact output.
import java.util.Scanner;
public class MovingBoxes
{
public static void main(String[] args)
{
Scanner input = new Scanner("Maple Street\n14 4 2.5");
String street = input.nextLine();
int boxes = input.nextInt();
int helpers = input.nextInt();
double poundsPerBox = input.nextDouble();
int boxesEach = boxes / helpers;
int leftOver = boxes % helpers;
double totalPounds = boxes * poundsPerBox;
System.out.println(street);
System.out.println(boxesEach);
System.out.println(leftOver);
System.out.println(totalPounds);
}
}Check your reasoning
Maple Street
3
2
35.0| Line | Call / work | Type | Stored |
|---|---|---|---|
| 8 | input.nextLine() |
String |
street ← "Maple Street" |
| 9 | input.nextInt() |
int |
boxes ← 14 |
| 10 | input.nextInt() |
int |
helpers ← 4 |
| 11 | input.nextDouble() |
double |
poundsPerBox ← 2.5 |
| 12 | 14 / 4 → 3 (integer division) |
int |
boxesEach ← 3 |
| 13 | 14 % 4 → 2 (remainder) |
int |
leftOver ← 2 |
| 14 | 14 * 2.5 → 35.0 |
double |
totalPounds ← 35.0 |
Line 12 drops the decimal part of 3.5 because both values are int; the 2 boxes that do not divide evenly appear as the remainder on line 13. Line 14 has a double, so the result prints as 35.0.
Reread 1.4.7 Reading Values with a Scanner and 1.4.3 Every Expression Has a Type if your output differed.
Question 21 · Multiple choice
A program reads the hours someone worked:
import java.util.Scanner;
public class HalfInput
{
public static void main(String[] args)
{
Scanner input = new Scanner("4.5");
int hours = input.nextInt();
System.out.println(hours);
}
}What happens when it runs?
- It prints
4. - It prints
4.5. - It does not compile, because
4.5is not anint. - It compiles, then stops with an
InputMismatchExceptionon line 8.
Check your reasoning
D. nextInt() can produce only a whole number. The next piece of input is 4.5, which is not one, so the Scanner throws an InputMismatchException when line 8 runs, and line 9 never runs.
- A is wrong:
nextInt()does not drop the decimal part the way integer division does. It refuses input that is not a whole number. - B is wrong:
hoursis anintandnextInt()produces anint, so 4.5 can never be stored or printed here. - C is wrong: the compiler checks the code, not the input text.
int hours = input.nextInt();stores anintin anint, which is compatible, so it compiles. The mismatch is discovered only while running.
Reread 1.4.7 Reading Values with a Scanner if you chose differently.
Question 22 · Multiple choice
Which statement about input and Scanner is true?
- A
Scanneris the only way a program can receive input. new Scanner(System.in)reads the keyboard,new Scanner("12 7")reads that text, and reading calls such asnextInt()work the same way for both.- The line
import java.util.Scanner;is optional, because every class in Java is available to every program. - A
Scannerreads all of the input into its variables the moment it is created.
Check your reasoning
B. The source of the text changes, but the reading calls behave the same, which is why this guide’s string-based examples show exactly how keyboard programs work.
- A is wrong: input can be tactile, audio, visual, or text, and
Scanneris one way to get text input. - C is wrong: without the import, the compiler reports
cannot find symbolforScanner. - D is wrong: creating a
Scanneronly sets it up. Each value is read when a call such asnextInt()runs, one piece at a time, in order, and stored by that line’s assignment.
Reread 1.4.6 Input and the Scanner Class and 1.4.7 Reading Values with a Scanner if you chose differently.
Reflection
Check each statement. If the answer is “not yet,” reread the linked subsection.
- I can use = to initialize a variable or change its value, and say what it holds afterward. Reread
- I can explain why the right side is evaluated before anything is stored, and why an assignment is not a formula. Reread
- I can find the type of an expression and decide whether it can be stored in a variable. Reread
- I can explain why a variable must be initialized before it is used in an expression. Reread
- I can explain what null means and which variables can hold it. Reread
- I can name forms of input and set up a Scanner, including its import line. Reread
- I can trace nextInt, nextDouble, and nextLine reading input in order. Reread