Open In App

Java Ternary Operator Puzzle

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the ternary operator is a simple way to perform conditional operations. It evaluates a condition and returns values depending on whether the condition is true or false. In this article, we will solve a Java program that uses the ternary operator with mixed operand types.

Understanding the Ternary Operator with Mixed Data Types in Java

Example:

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

Expected Output:

When we run this program, it will print:

X88

Key Concepts Behind the Conditional Operator

In Java, the ternary operator follows specific rules for determining the type of the result. Below are some rules which is very important to understand.

  • Same Type Operands: If both the second and third operands of the ternary operator are of the same type, then the result type of the expression is that type. This helps avoid mixed-type operations and simplifies the evaluation.
  • Constant Expression of Type int: 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, the type of the conditional expression is T.
  • Binary Numeric Promotion: When the second and third operands have different types, Java automatically converts smaller numeric types (like byte, short, or char) into int. This simply means the result will usually be of the int type.

Now, we are going to apply these rules to the code.

Applying Rules to the Code:

In the above code,

The first conditional expression is:

System.out.print(true ? x : 0);

Here, the operand x is of type char and 0 is of type int and the condition is true, the ternary operator returns x, which is char

Explanation: Here, the second operand 0 is a constant int and its value can be represented as a char because 0 is within the valid range for char. In this case the operands are compatible point 2 applies here and the result type is char and then the PrintStream.print(char) method is called, it prints the character X.

The second expression is:

System.out.print(false ? i : x);

Here, the operand i is of type int and x is of type char and the condition is false, the ternary operator returns x, which is a char

Explanation: The second operand x is a char and the first operand i is an int, here the operands are of different types and in this case binary numeric promotion converts the char to an int using its ASCII value. The ASCII value of X is 88, so the result is of type int and then the PrintStream.print(int) method is called, it prints 88.

After evaluating both conditional expressions, the program will produce the following output

Output:

X88

Next Article
Practice Tags :

Similar Reads