-3
class Example{
public static void main(String args[]){
char a='a';
System.out.println(a=='\u0061');
System.out.println(\u0061=='\u0061');
System.out.println(\u0061==97);
\u0061='\u0041';
System.out.println('A'=='\u0041');
System.out.println(65=='\u0041');
System.out.println(65==a);
System.out.println('\u0041'==a);        
}
}

Output : true*7

I can't understand this code. Please help

Thisura
  • 15
  • 7

2 Answers2

1

According to the Java Language Specification:

A Unicode escape of the form \uxxxx, where xxxx is a hexadecimal value, represents the UTF-16 code unit whose encoding is xxxx.

The unicode value for the character 'a' is 97 (61 in hex), and for 'A' is 65 (41 in hex). So the character \u0061 in your source is read as a, and the character \u0041 is read as A.

Your code is read as:

class Example{
    public static void main(String args[]){
        char a='a';
        System.out.println(a=='a');
        System.out.println(a=='a');
        System.out.println(a==97);
        a='A';
        System.out.println('A'=='A');
        System.out.println(65=='A');
        System.out.println(65==a);
        System.out.println('A'==a);        
    }
}
khelwood
  • 46,621
  • 12
  • 59
  • 83
-1
  1. char a='a'; - variable a stores a lowercase a character
  2. System.out.println(a=='\u0061'); - in UTF lowercase a character is represented as \u0061
  3. System.out.println(\u0061=='\u0061'); - \u0061 value is unquoted so it's decoded into lowercase a during compilation making it a=='\u0061', effectively the same as point 2.
  4. System.out.println(\u0061==97); - same as above because 97dec = 61hex except here we are not using UTF notation to represent character, instead we use numerical value of char
  5. \u0061='\u0041'; - a variable assigned value of \u0041 which is uppercase A
  6. System.out.println('A'=='\u0041'); - same as point 2
  7. System.out.println(65=='\u0041'); - 65dec = 41hex, same as point 4 but here we are comparing two constants, not the a variable.
  8. System.out.println(65==a); - see above
  9. System.out.println('\u0041'==a); - see above
Karol Dowbecki
  • 38,744
  • 9
  • 58
  • 89
  • "decoded into variable name during compilation" is misleading: it's decoded into the corresponding unicode symbol, `a`, which happens to be interpreted as a variable name in that specific context. – Andy Turner Feb 13 '19 at 10:54