Assignment Statements and Input
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.
- 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.
Codeint a = 5;
int b = a;
a = 10;
System.out.println(a + " " + b);
int c = a + b * 2;
System.out.println(c);Output10 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.
Codeint x = 3;
int y = 8;
int temp = x;
x = y;
y = temp;
System.out.println(x + " " + y);Output8 3null 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));=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). Scanneris one way to read input.
- 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 oldy.
- For long assignment sequences, keep a small table with one column per variable and update it line by line.
int x = 4;
int y = x * 2;
x = y - x;
y = y + x;Show answer
- Assignment inside expressions, like a = b = 4; or arr[i += 5].
- Any specific form of user input.