Java traps · Java

Java: 1 + 2 + "3" = 33?!PRO

Watch the video

Java reads + left to right: numbers add, then a String glues the rest as text. Brackets fix it — and a char bonus trap.

// 1 + 2 + "3" = 33 … but "1" + 2 + 3 = 123 ?!
// Java reads + left to right: numbers add until a String appears, then it glues text.
public class Main {
    public static void main(String[] args) {
        System.out.println(1 + 2 + "3");     // 33 ?!
        System.out.println("1" + 2 + 3);     // 123 ?!
        System.out.println("1" + (2 + 3));   // 15 ✓  brackets first
        System.out.println(1 + 2 + "" + 3);  // 33

        // Bonus: chars join the maths too
        System.out.println('1' + 2 + "3");   // 513 ?!  ('1' is 49)
    }
}
Open code J5 in Pocket Compiler Download the Pocket Compiler app — free

No app yet? Install it, then open the app and type the code J5 in Code Library.