Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading