Java Puzzlers笔记--puzzle 8: Dos Equis 选择操作符问题

public class DosEquis{
 public static void main(String[] args){
  char x = 'X';
  int i = 0;
  System.out.println(true  ? x : 0);
  System.out.println(false ? i : x);   
 }
}

Solution:
 显示:X88
 ?: 选择操作符的特别的地方:当选择的数有int类型出现时,char类型要转化为int显示;

TID:
 mixed-type computation can be confusing. Nowhere is this more apparent than in

conditional expressions.
 use the same type for the second and third operands  in conditional expressions.

 The rules for determining the result type of a conditional expression are too long

and complex to reproduce in their entirety, but here are three key points:
 1. If the second and third operands have the same type, that is the type of the

conditional expression. In other word, you can avoid the whole mess by steering clear of

mixed-type computation.
 2. If one of the operands is of type T where T is byte, short, or char and the other

operand is a constant expression of type int whose value is representable in type T, the

type of the conditional expression is T.
 3. Otherwise, binary numberic promotion is applied to the operand types, and the

type of the conditional expression is the promoted type of the second and third operands. 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值