简体   繁体   中英

Logic for Binary numeric promotion

Please explain me the logic for binary numeric promotion on the below code.

boolean flag = 'A' < 'a';
System.out.println(flag);// prints true.

In Java, the char primitive data type was defined as a 16-bit Unicode character, with values in the hexadecimal range from 0x0000 to 0xFFFF . When you compare two char values, it's that 16-bit hex value that's used.

In your specific case, A is represented by 0x0041 and a by 0x0061 , so 'A' < 'a' will evaluate to true .

For reference: Unicode (The Java Tutorials)

It's called promotion when you are comparing two different types (usually numbers) and one of them will be converted to the other so they can be compared. like:

int x = 5;
double y = 6;
if (x < y)
    ...

In Java int and double can be compared. In that case, int will be converted to double implicitly.

In your case there is no promotion. A character stored in memory as a number (in Java it's based UTF-16 standard and stored as exactly 2 bytes like a short ) and in 'A' < 'a' integer numbers are compared.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM