Sub topic 11
Choosing a Value with the Conditional Operator
Sometimes a program needs to choose between two values. For example, a score might lead to either "Pass" or "Try again".
The conditional operator, written with ? and :, makes this choice in one expression. An expression is a piece of code that produces a value. The conditional operator is also called the ternary operator because it has three parts:
condition ? valueIfTrue : valueIfFalse
The condition is an expression that produces a boolean value: either true or false. If the condition is true, Java uses the value before the colon. If it is false, Java uses the value after the colon.
A worked example
Save this program as ConditionalExample.java:
public class ConditionalExample {
public static void main(String[] args) {
int score = 72;
String result = score >= 60 ? "Pass" : "Try again";
System.out.println(result);
}
}Compile and run it:
javac ConditionalExample.java
java ConditionalExampleThe program prints Pass.
Here is how Java makes the choice:
- It checks
score >= 60. Becausescoreis 72, the condition is true. - It chooses
"Pass", the value after?. - It assigns that value to
result.
Change score to 45 and run the program again. The condition is now false, so the program prints Try again.
Only one choice is evaluated
Java checks the condition first. It then evaluates only the chosen expression. It does not evaluate the other one.
This matters when an expression would cause an error. For example, suppose total and count are both int variables:
int average = count != 0 ? total / count : 0;
If count is not zero, Java calculates total / count. If count is zero, Java chooses 0 without doing the division. This avoids dividing an integer by zero.
The 0 is a fallback value, not an actual average. Choose a fallback that makes sense for your program.
Choose compatible values
Both choices must work with the type of the variable receiving the result. In the score example, both choices are String values, and result is a String variable.
For now, keep the two choices the same type. For example, use two int values for an int result. Java has additional rules for some mixed types, so do not assume that any two types will work together.
Also include all three parts and both symbols. Leaving out the colon or the false choice makes the expression incomplete.
Practice
Exercise
What value does int price = 12; String label = price > 10 ? "High" : "Low"; assign to label?
Show answer
It assigns "High" because 12 is greater than 10.
Exercise
In count != 0 ? total / count : 0, is total / count evaluated when count is zero?
Show answer
No. The condition is false, so Java evaluates only the fallback value, 0.