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. 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章