Short on time? This page is the recap. For explanations and worked examples, use the full study guide.
Recap
- The assignment operator
=stores the value of the expression on its right in the variable on its left. It can initialize a variable or change its value. - A variable is initialized the first time it is assigned a value. A variable must be assigned a value before it is used in an expression.
- The assigned value must be of a compatible type.
- During execution an expression is evaluated to a single value, and that value has a type.
- A reference variable may hold an object reference or
null, a special literal meaning “no object”. - Input can take many forms.
Scanneris one way to read text from the keyboard.
Key relationships
| Idea | Example | Result |
|---|---|---|
| Update from itself | n = n + 1; |
n goes up by 1 |
| Right side uses old values | a = 3; a = a * 2 + a; |
a is 9 |
| int into double | double d = 5; |
d holds 5.0 |
| double into int | int n = 5.0; |
compile-time error |
| Use before assignment | int y; int z = y + 1; |
compile-time error (not initialized) |
| null | String s = null; |
legal; int n = null; is not |
nextInt() |
reads 42 |
the int 42 |
nextDouble() |
reads 3 |
the double 3.0 |
nextLine() after nextInt() |
on the same line | often "" (empty string) |
| Wrong input type | nextInt() reads abc |
InputMismatchException at run time |
Assumptions and conventions
- Examples use
Scanner in = new Scanner(System.in);withimport java.util.Scanner;at the top. - Any specific form of user input is outside the scope of the exam; reading and tracing assignments is what matters.
- Trace tables show a variable after each statement; a dash means it does not exist yet.
- Primitive assignment copies a value, so later changes to one variable do not affect the other.
Mistakes to avoid
- Reading
=as “equals”. It means “store”. - Using a variable before giving it a value.
- Storing a
doublein anintwithout conversion. - Working out the right side with values from later statements. Use the values as they are when the statement runs.
- Forgetting that
nextInt()leaves the rest of the line. - Assuming
nullis 0 or"". - Expecting the type of an input value to be fixed by what the user typed rather than by the method called.
Quick self-check
- After
int a = 4; a = a + a * 2;what isa? (a + a * 2is 4 + 8 = 12.) - After
int x = 5; int y = x; x = 9;what isy? (5:yholds its own copy.) - Does
double d = 3 / 2;compile, and what doesdhold? (Yes; the integer division gives 1, sodholds 1.0.) - What happens with
int y; System.out.println(y);? (It does not compile:ymight not have been initialized.) - If the user types
3.5whennextInt()is called, what happens? (AnInputMismatchExceptionat run time.)
Next: practice questions.