Java如何确定三元条件运算符表达式的类型?

ars*_*jii 3 java ternary-operator

有谁能解释一下?

public class Test {
    public static void main(String[] args) {
        char c = 'A';
        int i = 0;
        boolean b = true;

        System.out.println(b ? c : i);
        System.out.println(b ? c : (char)i);

        System.out.println(b ? c : 0);
        System.out.println(b ? c : (char)0);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

65
A
A
A.

从我站立的地方看起来确实很奇怪.我原以为只A打印出来.而且:怎么来的,当我取代0i输出的变化?输出似乎对所有值都相同i,而不仅仅是0.

hus*_*sik 5

如果要选择苹果与橙子,则必须提升其中一个(较小的一个):

public class Test {
  public static void main(String[] args) {
    char c = 'A';
    int i = 0;
    boolean b = true;

    System.out.println(b ? c : i);       // Promoted to int ---> 65
    System.out.println(b ? c : (char)i); // Not promoted ------> A (char vs char)

    System.out.println(b ? c : 0);       // Not promoted vs null/0
    System.out.println(b ? c : (char)0); // Not promoted vs char
  }
}
Run Code Online (Sandbox Code Playgroud)

如果有一个变量类型,nibble那么在选择时你就不会得到不同的输出.

System.out.println(b ? c : (nibble)i); // I know there is no nibble. :)
                                       // nibble promotes to char.
                                       // I know... there is no nibble.
                                       //so, output is A
Run Code Online (Sandbox Code Playgroud)