How does Java decide the type of a ternary conditional operator expression?

时光怂恿深爱的人放手 提交于 2020-01-04 04:00:50

问题


Can anyone explain this?

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);
    }
}

Output:

65
A
A
A

It sure looks strange from where I'm standing. I would have expected only As to print out. And moreover: how come when I substitute 0 for i the output changes? The output seems to be the same for all values of i, not just 0.


回答1:


From the Java Language Specification, about type conversion and promotion (see the text in bold)

EVERY expression written in the Java programming language has a type that can be deduced from the structure of the expression and the types of the literals, variables, and methods mentioned in the expression. It is possible, however, to write an expression in a context where the type of the expression is not appropriate. In some cases, this leads to an error at compile time. In other cases, the context may be able to accept a type that is related to the type of the expression; as a convenience, rather than requiring the programmer to indicate a type conversion explicitly, the Java programming language performs an implicit conversion from the type of the expression to a type acceptable for its surrounding context.

The type conversion in your case that happens at compile time explains the output.

In the cases where i was involved, c has been promoted to integer.

In the cases where 0 was involved, it is treated as character and hence c remained as character.




回答2:


When you want to select apples vs oranges, you must promote one of them (the lesser one):

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
  }
}

If there was a variable type such as nibble then you would not get a different output when selecting.

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


来源:https://stackoverflow.com/questions/12332574/how-does-java-decide-the-type-of-a-ternary-conditional-operator-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!