简体   繁体   中英

Ternary operator casts integer

Please have a look into the below code

int a =10;
int b =20;
System.out.println((a>b)?'a':65);//A
System.out.println((a>b)?a:65);//65
System.out.println((a>b)?"a":65);//65

Can somebody explain me why it is displaying "A" if I made variable 'a' as a character? And it should display 65 if I made "a" as a string?

This behavior is documented in the JLS - 15.25. Conditional Operator ? : :

If one of the operands is of type T where T is byte, short, or char, and the other operand is a constant expression ( §15.28 ) of type int whose value is representable in type T, then the type of the conditional expression is T

When you write

(a > b) ? 'a' : 65

the second type is converted to a char .

Go through the JLS, it explains the behavior (same approach) in other cases.

当你的System.out.println((a>b)?'a':65);//A被执行时,JVM 看到你的条件是假的,所以它会输出 65。现在,你已经提供了 'a'作为第一个可能的输出,65 将转换为 char 并返回 'A',其 ASCII 值为 65。

Ternary Operator work as if-then-else statement. Your getting those result because of autoboxing/unboxing rules for the conditional operator mentioned in JLS section 15.25

first line System.out.println((a>b)?'a':65); condition is false so else block will print value of else block is treated as char because if block contain a char variable.

Second line System.out.println((a>b)?a:65); condition is false so else block will print value of else block is treated as int because if block contain a int variable. here 65 is int value.

Third line System.out.println((a>b)?"a":65); condition is false so else block will print value of else block is treated as String because if block contain a String variable. here 65 is a String not int.

I have checked the JLS. for more info refer official JLS here

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