Search code examples
javaternary

Ternary operator returns an unexpected output


This subject is already asked but I didn't understand it. You'll find my program below. When I run this program it prints X and 88. When I remove do the declaration of int i = 0 it returns X and X. I found some explanations here : Unexpected output when using a ternary operator and final variable but i didn't understand it so much. I don't understand why this program returns X and 88 instead of X and X.

public class Ternary {
    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

  • please read the rules of ternary operator here

    https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

    1st one is result of 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, then the type of the conditional expression is T. T being type char in this case and constant expression being 0

    so the output is of type char which is x


    2nd one is case for Otherwise, binary numeric promotion is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

    read about binary numeric promotion here https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html#jls-5.6.2

    last case of point 2 applies here Otherwise, both operands are converted to type int. and converting char to int gives its ascii value which is 88

    and hence the output is 88