Ternary operator casts integer

前端 未结 3 1333
情歌与酒
情歌与酒 2020-12-21 15:25

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


        
3条回答
  •  無奈伤痛
    2020-12-21 16:28

    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

提交回复
热议问题