Skip to lesson

Operator, Division and Overflow Puzzles

Written tests and live rounds are full of "what is the output?" questions on operators. The interviewer is checking that you trace line by line instead of guessing, and that you know the handful of rules these puzzles hide behind.

How to trace: write variable values line by line

Tracing means running code by hand and writing down every variable's value after each line, in a small table, instead of guessing the result from a quick glance.

Five lines change three variables. Step through the program below and watch a, b and c change, applying the side effects in left-to-right order.

Example 1 · Trace a short program with a table

TraceDemo.javaJava
public class TraceDemo {    public static void main(String[] args) {        int a = 5;        int b = a++ * 2;   // b = 5 * 2 = 10, then a = 6        int c = --a + b;   // a = 5 first, c = 5 + 10 = 15        a += c % 4;        // 15 % 4 = 3, a = 5 + 3 = 8        System.out.println("a=" + a + " b=" + b + " c=" + c);    }}
Output
a=8 b=10 c=15

What this code does

  • Trace table (a, b, c): line 1 → 5, -, -; line 2 → 6, 10, -; line 3 → 5, 10, 15; line 4 → 8, 10, 15.
  • a++ * 2 uses the old a (5), and the increment happens right after the operand is read.

For each line, work out the right-hand side with the values before the line, then apply the side effects. Do it the same way every time:

  • Draw a column for each variable and add a row per line.
  • x++ gives the old value, ++x the new one.
  • *, / and % come before + and -; assignment is last.
  • Write the printed text exactly, including spaces.

Revise: Operator precedence (opens in a new tab).

Trace the code

Trace a, b and c line by line

public class TraceSteps {
public static void main(String[] args) {
int a = 5;
int b = a++ * 2;
int c = --a + b;
a += c % 4;
System.out.println("a=" + a + " b=" + b + " c=" + c);
}
}

Variables

a
5

Output

(nothing printed yet)

Line 3a starts at 5.

Step 1 of 5

i++ + ++i and compound assignment casts

A compound assignment such as b += 5 means b = (byte) (b + 5): it includes a hidden cast to the type of the variable. That is why it compiles where b = b + 5 does not, and why it can wrap silently.

The program traces i++ + ++i, j = j++, a compound += on k and a byte that wraps. Predict r, j, k, b and grade before you read the output.

Example 2 · Increment and compound assignment puzzles

IncrementPuzzleDemo.javaJava
public class IncrementPuzzleDemo {    public static void main(String[] args) {        int i = 5;        int r = i++ + ++i;        System.out.println("r=" + r + ", i=" + i);
        int j = 5;        j = j++;        System.out.println("j=" + j);
        int k = 1;        k += k++ + ++k;        System.out.println("k=" + k);
        byte b = 120;        b += 10;            // means b = (byte) (b + 10)        System.out.println("b=" + b);
        char grade = 'A';        grade += 2;        System.out.println("grade=" + grade);    }}
Output
r=12, i=7
j=5
k=5
b=-126
grade=C

What this code does

  • i++ + ++i: the left operand is 5 (i becomes 6), the right one makes i 7 and gives 7, so 12. j = j++ assigns the saved old value 5 back.
  • k += k++ + ++k saves k = 1 first, then adds 1 + 3, so k is 5. b += 10 hides a cast to byte: 130 wraps to -126.

Post-increment i++ gives the old value and then adds 1; pre-increment ++i adds 1 first. Java evaluates operands left to right, so i++ + ++i with i = 5 is 5 + 7 = 12. In i = i++ the saved old value is assigned back, so i is unchanged. The hidden cast can overflow: a byte at 120 plus 10 becomes -126.

Revise: Arithmetic operators (opens in a new tab).

Predict the output

Which value is left?

Read each program and pick what it prints.

Round 1 of 3

A post-increment inside a sum.

public class IncRound1 {
public static void main(String[] args) {
int x = 10;
int y = x++ + x;
System.out.println(x + " " + y);
}
}

Integer division, % with negatives, char and String order

Numeric promotion means byte, short and char values become int before arithmetic, and a long, float or double operand makes the whole operation use that wider type.

The program prints integer division, remainders with negatives, chars, and Strings joined in different orders. Work out each line before you check the output.

Example 3 · Division, remainder, chars and concatenation order

DivisionStringDemo.javaJava
public class DivisionStringDemo {    public static void main(String[] args) {        System.out.println(7 / 2 + " " + -7 / 2 + " " + 7 / 2.0);        System.out.println(-7 % 3 + " " + 7 % -3);        System.out.println('A' + 1);        System.out.println((char) ('A' + 1));        System.out.println("" + 1 + 2);        System.out.println(1 + 2 + "");        System.out.println('a' + 'b' + "c");        System.out.println("c" + 'a' + 'b');        System.out.println(1.0 / 0 + " " + 0.0 / 0);        try {            System.out.println(1 / 0);        } catch (ArithmeticException e) {            System.out.println("ArithmeticException: " + e.getMessage());        }    }}
Output
3 -3 3.5
-1 1
66
B
12
3
195c
cab
Infinity NaN
ArithmeticException: / by zero

What this code does

  • Integer division cuts toward zero, and % follows the sign of the left number. 7 / 2.0 is a double division, so 3.5.
  • 'a' + 'b' adds the codes 97 + 98 = 195 before the String appears; "c" + 'a' is already text, so the chars are joined.
  • Dividing doubles by zero gives Infinity or NaN; dividing ints by zero throws.

Integer division cuts toward zero: 7 / 2 is 3 and -7 / 2 is -3. The remainder % takes the sign of the left operand. An int divided by zero throws ArithmeticException; a double gives Infinity or NaN. A char in arithmetic is its number, and + groups left to right: 1 + 2 + "" is "3", but "" + 1 + 2 is "12".

Revise: Type conversion and casting (opens in a new tab).

Find the bug

Why is the output wrong?

Tap the line that gives the wrong result.

The average of 7 and 2 items should print 3.5 but prints 3.0.

Round 1 of 3

Overflow: Integer.MAX_VALUE + 1 and multiplying before widening

Overflow is a result that is too big for its type. int and long arithmetic wraps around silently: Integer.MAX_VALUE + 1 becomes Integer.MIN_VALUE, and no error is thrown.

The program adds 1 to the largest int, multiplies int literals into a long, takes Math.abs of the smallest int and averages two big numbers.

Example 4 · Overflow that compiles and runs quietly

OverflowDemo.javaJava
public class OverflowDemo {    public static void main(String[] args) {        int max = Integer.MAX_VALUE;        System.out.println("MAX + 1      = " + (max + 1));
        long wrong = 24 * 60 * 60 * 1000 * 1000;    // int math, then widened        long right = 24L * 60 * 60 * 1000 * 1000;   // long math from the start        System.out.println("micros/day   = " + wrong + " (wrong)");        System.out.println("micros/day   = " + right);
        System.out.println("abs(MIN)     = " + Math.abs(Integer.MIN_VALUE));
        int low = 2_000_000_000;        int high = 2_100_000_000;        System.out.println("(low+high)/2 = " + (low + high) / 2);        System.out.println("safe mid     = " + (low + (high - low) / 2));
        try {            Math.multiplyExact(100_000, 100_000);        } catch (ArithmeticException e) {            System.out.println("multiplyExact: " + e.getMessage());        }    }}
Output
MAX + 1      = -2147483648
micros/day   = 500654080 (wrong)
micros/day   = 86400000000
abs(MIN)     = -2147483648
(low+high)/2 = -97483648
safe mid     = 2050000000
multiplyExact: integer overflow

What this code does

  • Every literal in 24 * 60 * 60 * 1000 * 1000 is an int, so the product wraps before it is stored in the long. One L on the first number fixes it.
  • Math.abs(Integer.MIN_VALUE) stays negative, and low + high overflows, so the midpoint is wrong. The Exact methods throw instead of wrapping.

The sneaky case is 24 * 60 * 60 * 1000 * 1000 stored in a long: every literal is an int, so the product wraps before it is widened. Write 24L * ... instead. In binary search, (low + high) / 2 can overflow, so use low + (high - low) / 2. Math.addExact and Math.multiplyExact throw instead of wrapping.

Revise: Integer numbers (opens in a new tab).

Fix the error

Fix the number error

Read the error, then pick the line that fixes it.

Round 1 of 2

A turnover figure of three billion will not compile.

public class BigFee {
public static void main(String[] args) {
long total = 3000000000;
System.out.println(total);
}
}

Error

BigFee.java:3: error: integer number too large

Floating point: 0.1 + 0.2 and == on doubles

A tolerance compare checks that two doubles are close enough, for example Math.abs(a - b) < 1e-9, instead of using ==, because decimals such as 0.1 cannot be stored exactly in binary.

The program adds 0.1 and 0.2, compares doubles with == and with a tolerance, then tries NaN, casts and Math.round.

Example 5 · Floating-point surprises

FloatingPointDemo.javaJava
import java.math.BigDecimal;
public class FloatingPointDemo {    public static void main(String[] args) {        System.out.println(0.1 + 0.2);        System.out.println(0.1 + 0.2 == 0.3);        System.out.println(Math.abs(0.1 + 0.2 - 0.3) < 1e-9);        System.out.println(0.1f == 0.1);        System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2")));
        double nan = 0.0 / 0;        System.out.println((nan == nan) + " " + Double.isNaN(nan));        System.out.println((int) 3.99 + " " + (int) -3.99);        System.out.println(Math.round(2.5) + " " + Math.round(-2.5));    }}
Output
0.30000000000000004
false
true
false
0.3
false true
3 -3
3 -2

What this code does

  • 0.1 and 0.2 are stored as close binary values, so their sum is slightly above 0.3 and == fails; a tolerance check passes, and BigDecimal from Strings is exact.
  • NaN is not equal even to itself, so use Double.isNaN. A cast to int cuts toward zero, while Math.round rounds half up, so -2.5 becomes -2.

A double stores numbers in binary, and 0.1 has no exact binary form, just as 1/3 has no exact decimal form. For money, use BigDecimal built from a String, or whole paise in a long. Also remember that NaN == NaN is false (use Double.isNaN), a cast to int cuts toward zero, and Math.round(-2.5) is -2.

Revise: Decimal numbers (opens in a new tab).

Predict the output

Exact or not?

Read each program and pick what it prints.

Round 1 of 3

Adding two simple decimals.

public class FloatRound1 {
public static void main(String[] args) {
System.out.println(0.1 + 0.2);
}
}

Next step

Check your understanding

12 quick questions