![]() |
VOOZH | about |
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.
Example:
Expected Output:
When we run this program, it will print:
X88In Java, the ternary operator follows specific rules for determining the type of the result. Below are some rules which is very important to understand.
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