Tricky Output Questions: Types, Overflow and Overloading

Difficulty: Intermediate

Question

Predict the output of these tricky snippets: floating-point comparison, string concatenation order, char arithmetic, integer overflow, Math.abs(MIN_VALUE), overload resolution with null, and i = i++.

Answer

Output-prediction questions are the favourite filter in the first written round of service-company hiring, and they show up in product companies as warm-ups too. The trick is not memorizing answers but knowing a handful of rules that generate them. Let me go through the rules using the classic puzzles.

Rule one: floating point is binary. 0.1 and 0.2 cannot be represented exactly in binary, so 0.1 + 0.2 is 0.30000000000000004, and 0.1 + 0.2 == 0.3 is false. Never compare doubles with ==; use a tolerance, or BigDecimal (constructed from a String, not a double) for money.

Rule two: the plus operator evaluates left to right, and once a String appears, the rest is concatenation. So "" + 1 + 2 is "12" (string, then 1 appended, then 2 appended), while 1 + 2 + "" is "3" (numeric addition first, then converted). If you have a null String, "x" + s prints xnull.

Rule three: char is a numeric type. In c + 1 where c is a char, the operands are promoted to int, so 'a' + 1 is the int 98. To get a character you must cast: (char)(c + 1) gives b. Likewise 'a' + 'b' is 97 + 98 = 195, an int, not a String. Note the subtlety with compound assignment: c += 1 works and keeps the char type because compound operators include an implicit cast. The same reasoning explains why byte b = 10; b = b + 1 fails to compile while b += 1 compiles.

Rule four: integers wrap around silently. Integer.MAX_VALUE + 1 is Integer.MIN_VALUE, which is -2147483648, with no exception. And because the negative range has one more value than the positive range, Math.abs(Integer.MIN_VALUE) has no positive counterpart and returns Integer.MIN_VALUE itself, still negative. When you need overflow detection, use Math.addExact and friends, which throw ArithmeticException.

Rule five: overload resolution picks the most specific applicable method at compile time. If you have m(Object) and m(String) and call m(null), both are applicable, but String is more specific, so m(String) is chosen. If you had m(String) and m(Integer), the same call would be ambiguous and would not compile. Remember that overloads are resolved by the compile-time type of the arguments, while overriding is resolved at runtime by the actual object type.

Rule six: post-increment returns the old value. In i = i++, the expression i++ evaluates to the old value 0, increments i to 1, and then the assignment overwrites i with the old value 0. So i stays 0. Compare with i = ++i, which gives 1.

A few more you might see: integer division 5 / 2 is 2, not 2.5; 5 / 2.0 is 2.5; -7 % 3 is -1 because the sign of the remainder follows the dividend; and (int) 3.99 is 3 because casting truncates.

When you get one of these in an interview, narrate the rule aloud before answering. Even if you slip on the final answer, the interviewer sees a correct thought process, and that earns much more credit than a silent guess.

Code examples

Numeric and string puzzles

public class Tricky1 {
    public static void main(String[] args) {
        System.out.println(0.1 + 0.2 == 0.3);
        System.out.println("" + 1 + 2);
        System.out.println(1 + 2 + "");
        char c = 'a';
        System.out.println(c + 1);
        System.out.println((char) (c + 1));
        System.out.println(Math.abs(Integer.MIN_VALUE));
        System.out.println(Integer.MAX_VALUE + 1);
        System.out.println('a' + 'b');
        String s = null;
        System.out.println("x" + s);
    }
}

Each line follows one of the rules: binary floating point, left-to-right concatenation, char promotion to int, and silent integer wrap-around.

Overloading with null and post-increment

public class Tricky2 {
    static void m(Object o) {
        System.out.println("Object");
    }

    static void m(String s) {
        System.out.println("String");
    }

    public static void main(String[] args) {
        m(null);
        int i = 0;
        i = i++;
        System.out.println(i);
        int j = 0;
        j = ++j;
        System.out.println(j);
        System.out.println(-7 % 3);
    }
}

String is the most specific overload for null. i = i++ stores the old value back into i. The remainder takes the sign of the dividend.

Key points

Common follow-up questions

Interview tips

Concepts covered

Type Promotion, Integer Overflow, String Concatenation, Overload Resolution, Floating Point

More Core Java & Collections questions