AP Computer Science A · Unit 1 lecture · Part 4 of 11 · 10 min

1.4 Assignment and input · 1.5 Casting and range of variablesStore it, convert it, know its limits

Mr. Thompkins
The = sign in Java is not the = from math class. It's an instruction: "work out the right side, then put the answer in the box on the left." Once that clicks, a line like x = x + 1 stops looking like nonsense.

An assignment statement evaluates the expression on the right side completely, and only then stores the result in the variable on the left, replacing whatever was there. The old value is gone for good. A variable must be declared before you assign to it, and it must have a value before you read it. Using a local variable that was never given a value doesn't compile.

?Wait, what's the difference between = and ==?
= is assignment: it stores a value. == is a comparison: it asks whether two values are equal and gives back true or false. You'll use == in Unit 2. Writing x = 5 says "put 5 in x". Writing x == 5 asks "is x 5?"

Because assignment replaces the old value, swapping two variables takes three steps and a temporary variable. If you write a = b; b = a;, the first line already destroyed a's value, so both end up holding 9.

Statementabtemp
int a = 5;5
int b = 9;59
int temp = a;595
a = b;995
b = temp;955
A trace table for a swap: one row per statement, one column per variable. This is the single most useful tool in AP CSA.

Programs can also get values from input: a user typing, a file, a sensor. Java's Scanner class can read the keyboard, but on the AP exam values arrive as parameters, and you never write keyboard input. Scanner returns in Unit 4, for text files.

Casting

A cast converts a value to another type. You write the type in parentheses in front of the value. (double) 7 is 7.0. (int) 7.8 is 7: casting a double to an int truncates, dropping everything after the decimal point and moving toward zero. It never rounds, so (int) 7.99 is still 7, and (int) -7.8 is -7.

Java does int to double for you (that's called widening), because nothing can be lost. It refuses to do double to int on its own, because the decimal part would be lost, so you must cast. A cast applies only to the value right after it. (double) 7 / 2 casts the 7 first, so the division is 7.0 / 2, which is 3.5. (double) (7 / 2) divides first, with ints, getting 3, and then casts 3 to 3.0.

-3-2-101232.7-2.7(int) 2.7 is 2(int) -2.7 is -2casting to int chops toward zeroit never roundsto round x >= 0: (int) (x + 0.5)
Truncation moves toward zero on both sides of the number line. To round to the nearest int, add 0.5 first (or subtract 0.5 for a negative number), then cast.

To round a nonnegative double to the nearest whole number, add 0.5 and then cast: (int) (x + 0.5). For x = 7.8 that's (int) 8.3, which is 8. For x = 7.2 it's (int) 7.7, which is 7. For a negative x, subtract instead: (int) (x - 0.5).

The limits of int and double

An int is stored in 32 bits, so it can only hold values from Integer.MIN_VALUE, which is -2147483648, to Integer.MAX_VALUE, which is 2147483647. If an int calculation goes past either end, it overflows: the value wraps around to the other end, and Java gives no error and no warning. Integer.MAX_VALUE + 1 is Integer.MIN_VALUE.

?Wait, what's a bit?
A bit is a single binary digit: 0 or 1. Computers store everything as patterns of bits. With 32 bits there are 2 to the 32nd power (about 4.3 billion) different patterns, and an int splits them between negative numbers, zero and positive numbers. That's why its range stops near 2.1 billion in each direction.

doubles have a different weakness. Many decimals, like 0.1, have no exact binary form, so the computer stores a value that is extremely close but not exact. Those tiny differences are called round-off error, and they can show up in output: 0.1 + 0.2 prints 0.30000000000000004. The practical rule: be careful comparing two computed doubles with ==.

1double x = 7.8;2int n = (int) x;13int m = (int) -x;14int r = (int) (x + 0.5);25double avg = (double) (4 + 5) / 2;36System.out.println(n + " " + m + " " + r + " " + avg);7System.out.println(Integer.MAX_VALUE + 1);48System.out.println(0.1 + 0.2);5
  1. line 2-3 Truncate toward zero: 7 and -7
  2. line 4 8.3 truncates to 8: rounded
  3. line 5 Cast 9 to 9.0 first, so 9.0 / 2 is 4.5
  4. line 7 Overflow wraps around, with no error
  5. line 8 Round-off: 0.1 has no exact binary form
output › 7 -7 8 4.5 -2147483648 0.30000000000000004
Casting, rounding, overflow and round-off, run under Java 17.
Pause and think
A student writes double avg = (7 + 8) / 2; and expects 7.5. What does avg hold, and what is the smallest change that fixes it?
I thought about it. Show me
avg holds 7.0. The right side is evaluated first, with ints: 15 / 2 is 7. Only then is 7 widened to 7.0 for storage. The fix is to get a double into the division itself: (7 + 8) / 2.0, or (double) (7 + 8) / 2.
Average, then round

A teacher's grading program has these lines. What is printed?

int total = 437;
int count = 6;
int wrong = total / count;
double avg = (double) total / count;
int rounded = (int) (avg + 0.5);
System.out.println(wrong + " " + avg + " " + rounded);
  1. wrong: total / count is int / int. 437 / 6 is 72 (6 × 72 is 432, remainder 5). wrong is 72.
    Why?
    Integer division drops the remainder, so the average is cut short. That's the logic error from section 1.
  2. avg: (double) total turns 437 into 437.0 first. Then 437.0 / 6 is a double division: 72.83333333333333.
    Why?
    The cast binds to total only. One double operand is enough to make the whole division a double division.
  3. rounded: avg + 0.5 is 73.33333333333333. (int) truncates it to 73.
    Why?
    Adding 0.5 before truncating pushes anything from .5 up into the next whole number. That's rounding.
  4. Printing joins them with spaces: 72 72.83333333333333 73.

Answer: 72 72.83333333333333 73

Stuck? Get a hint
  1. For wrong, both operands are int. How many whole times does 6 go into 437?
  2. For avg, the cast happens before the division. Is it a double division now?
  3. For rounded, add 0.5 to avg, then chop off the decimals.
Check yourself
Which expression evaluates to 3.5?
  1. A(double) (7 / 2)
  2. B(double) 7 / 2
  3. C(int) 7.0 / 2
  4. D7 / 2 * 1.0
Show the answer

B. The cast turns 7 into 7.0 before dividing, so 7.0 / 2 is 3.5. Choice A is the top trap: the parentheses make 7 / 2 happen first, with ints, giving 3, and the cast makes it 3.0. Choice D also divides first: 3 * 1.0 is 3.0.

Check yourself
What is printed?
int big = Integer.MAX_VALUE;
big = big + 1;
System.out.println(big);
  1. A2147483648
  2. B-2147483648
  3. C2147483647
  4. DAn ArithmeticException is thrown
Show the answer

B. big + 1 goes past Integer.MAX_VALUE, so the int overflows and wraps around to Integer.MIN_VALUE, -2147483648. There is no exception (choice D): int overflow is silent. Choice A is what math says, but an int can't hold it.

  • Assignment: evaluate the whole right side, then store it on the left. The old value is gone.
  • (int) truncates toward zero. (int) (x + 0.5) rounds a nonnegative x.
  • A cast applies to the value right after it: (double) 7 / 2 is 3.5, (double) (7 / 2) is 3.0.
  • int runs from Integer.MIN_VALUE to Integer.MAX_VALUE. Past the end, it wraps around with no error.
  • doubles can have round-off error: 0.1 + 0.2 is not exactly 0.3.