Sunday, November 17, 2024
Google search engine
HomeLanguagesJavaJava Ternary Operator Puzzle

Java Ternary Operator Puzzle

Find the output of the program




public class GFG {
    public static void main(String[] args) {
    char x = 'X';
    int i = 0;
    System.out.print(true ? x : 0);
    System.out.print(false ? i : x);
    }
}


Solution:
If you run the program,you found that it prints X88. The first print statement prints X and the second prints 88.

The rules for determining the result type of a conditional expression are too long and complex to reproduce in their entirety, but here are three key points.

  1. If the second and third operands have the same type, that is the type of the conditional expression. In other words, you can avoid the whole mess by steering clear of mixed-type computation.
  2. 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 re-presentable in type T, the type of the conditional expression is T.
  3. 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.

Points 2 and 3 are the key to this puzzle. In both of the two conditional expressions in the program, one operand is of type char and the other is of type int. In both expressions, the value of the int operand is 0, which is representable as a char. Only the int operand in the first expression, however, is constant (0); the int operand in the second expression is variable (i). Therefore, point 2 applies to the first expression and its return type is char. Point 3 applies to the second conditional expression, and its return type is the result of applying binary numeric promotion to int and char, which is int.

The type of the conditional expression determines which overloading of the print method is invoked. For the first expression, PrintStream.print(char) is invoked; for the second, PrintStream.print(int). The former overloading prints the value of the variable x as a Unicode character (X), whereas the latter prints it as a decimal integer (88).

This article is contributed by Shubham Juneja. If you like Lazyroar and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the Lazyroar main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

RELATED ARTICLES

Most Popular

Recent Comments