-5
public static void main(String[] args) {
        char alpha = 'A';
        int foo = 65;
        boolean trueExp = true;
        System.out.println(trueExp ? alpha : 0);
        System.out.println(trueExp ? alpha : foo);
    }
run result:A
           65

I can’t know the first output is A.who can explian ? thank you!

JunChen
  • 41
  • 1
  • 3

1 Answers1

2

From JLS 15.25.2:

If one of the operands [of the conditional ? : operator] is of type T where T is byte, short, or char, and the other operand is a constant expression (§15.29) of type int whose value is representable in type T, then the type of the conditional expression is T.

System.out.println(trueExp ? alpha : 0);

alpha is a char, 0 is an int with a constant expression which is representable by char, hence the result of the conditional expression is a char.

System.out.println(trueExp ? alpha : foo);

Here, foo is not a constant expression, so the operands will undergo binary numeric promotion to int, hence it prints (int) alpha, 65.

If you were to declare final int foo, it would print A once again (Ideone demo).

Andy Turner
  • 137,514
  • 11
  • 162
  • 243