Ternary operator casts integer

前端 未结 3 1348
情歌与酒
情歌与酒 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:30

    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.

提交回复
热议问题