Search code examples
javacharequalityprimitive-types

why ch1 == ch2 is false, doesn't it hold the same char values?


I'm trying to compare two char primitives ch1 and ch2. Both are assigned the value 1 as shown below.

But when compared using the "==" operator it returns false, which I don't understand how or what's happening behind the scenes.

char ch1 = (char)1;
char ch2 = '1';
System.out.println(ch1==ch2); //false

//further comparisions
System.out.println(ch1 == 1);       //true
System.out.println(ch1 == '\u0031'); //false

System.out.println(ch2 == 1);       //false
System.out.println(ch2 == '\u0031'); //true

Solution

  • '1' has the value 49 (31 hexadecimal).

    (char)1 has the value 1.

    A char is just a 16-bit integer. The notation 'x' means 'the character code for the character x', where the encoding used in Java is Unicode, specifically UTF-16.

    The cast (char) does not change the value of the expression to its right, except that it truncates it from a full-size integer to 16 bits (which is no change for values 0 to 65535).