Java traps · Java

Java: 'a' + 'b' = 195?!FREE

Watch the video

A char is secretly a number ('a' is 97). See why + adds them, and how to join them as text.

// 'a' + 'b' = 195 ?!  — a char is secretly a number: 'a' is 97, 'b' is 98.
public class Main {
    public static void main(String[] args) {
        char a = 'a', b = 'b';

        System.out.println(a + b);        // 195 ?!   (97 + 98)
        System.out.println("" + a + b);   // ab ✓     (start with a String)
        System.out.println((int) a);      // 97
        System.out.println((char) (a + 1)); // b      (next letter)
    }
}
Open code J2 in Pocket Compiler Download the Pocket Compiler app — free

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