ACSA Exam Prep
Unit 1 · Using Objects and Methods · Topic 1.4

Assignment Statements and Input

Skill 2.ASkill 4.A

Big idea: The = sign means "compute the right side, then store it on the left." It copies a value at one moment in time; it does not link two variables together.

Learning objectives
  • Develop code for assignment statements with expressions and determine the value that is stored in the variable as a result of these statements.
  • Develop code to read input.

How assignment works

Java evaluates the whole right side first, using the variables' current values, then stores the result in the variable on the left. That is why count = count + 1 makes sense in code even though it is false in algebra.

A variable must have a value before you use it. Its first assignment initializes it.

Code
int a = 5;
int b = a;
a = 10;
System.out.println(a + " " + b);
int c = a + b * 2;
System.out.println(c);
Output
10 5
20

Swapping two variables

Because assignment overwrites, swapping needs a temporary variable to hold one value. This pattern shows up in sorting algorithms later.

Code
int x = 3;
int y = 8;
int temp = x;
x = y;
y = temp;
System.out.println(x + " " + y);
Output
8 3

null and reading input

A reference variable can hold null, which means it refers to no object yet.

The Scanner class reads input. nextInt(), nextDouble(), and next() read one token; nextLine() reads the rest of the line. The exam won't test a particular kind of user input, but you should recognize these calls.

Scanner in = new Scanner(System.in);
System.out.print("Age? ");
int age = in.nextInt();
System.out.println("Next year you'll be " + (age + 1));
Key points
  • = evaluates the right side, then stores it in the variable on the left.
  • Assignment copies the current value. Later changes to one variable don't affect the other.
  • Every expression evaluates to one value with one type.
  • A reference variable can hold null (no object).
  • Scanner is one way to read input.
Watch out
  • Using a local variable before it is assigned is a compile-time error.
  • x = y; y = x; does not swap; both end up equal to the old y.
Exam tip
  • For long assignment sequences, keep a small table with one column per variable and update it line by line.
Quick check
What are x and y?
int x = 4;
int y = x * 2;
x = y - x;
y = y + x;
Show answer
x is 4 and y is 12. y starts at 8, x becomes 8 - 4 = 4, then y becomes 8 + 4 = 12.
Not on the exam
  • Assignment inside expressions, like a = b = 4; or arr[i += 5].
  • Any specific form of user input.