0

Consider the below code snippet using ternary operator in print statement

public static void main(){
    char a='A';
    int i=0;
    System.out.println(true?a:0);
    System.out.println(false?i:a);
}

The output of the above snipped is:

A 
65

Why is the output not as below:

A
A
maloomeister
  • 2,461
  • 1
  • 12
  • 21
  • 2
    Does this answer your question? [Ternary operator with different types of expressions](https://stackoverflow.com/questions/50839244/ternary-operator-with-different-types-of-expressions) – crimson589 Nov 04 '21 at 06:37
  • 1
    65 happens to be the ASCII (byte) code for `'A'`. The ternary operator yields a common type,`int`. – Andrej Podzimek Nov 04 '21 at 06:40
  • The conversion is clearly mentioned in the docs https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#:~:text=The%20type%20of%20a%20conditional%20expression,of%20the%20conditional%20expression%20is%20T. – Giriteja Bille Nov 04 '21 at 06:48
  • @AndrejPodzimek yes 65 is ASCII code for 'A'. If its common state then even the first print should be printing 65 right. – prajwal dcunha Nov 04 '21 at 09:36
  • @prajwaldcunha No. `System.out.println(true?a:i);` would be printing 65. But a literal `0` is not the same thing as `i`. – Andrej Podzimek Nov 04 '21 at 09:48

0 Answers0