Sub topic 11
Choosing a Value with the Conditional Operator
Sometimes a program needs one of two values. For example, a test score may produce the label "Pass" or "Try again". Java’s conditional operator lets you choose between those values 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 operands, or parts:
condition ? valueIfTrue : valueIfFalseThe condition is an expression that produces a boolean value: true or false. If the condition is true, Java uses the expression after ?. If it is false, Java uses the expression after :.
A worked example
This program chooses a result label from a score. It then makes the same choice with an if statement, which runs code when a condition is true.
public class ConditionalDemo {
public static void main(String[] args) {
int score = 72;
String result = score >= 60 ? "Pass" : "Try again";
System.out.println(result);
String resultWithIf;
if (score >= 60) {
resultWithIf = "Pass";
} else {
resultWithIf = "Try again";
}
System.out.println(resultWithIf);
}
}Save the code as ConditionalDemo.java, compile it, and run it. The output is:
Pass
PassHere is how Java works through the conditional expression:
- It checks
score >= 60. With a score of72, the condition istrue. - It chooses the expression after
?, which is"Pass". - The conditional expression produces
"Pass". - The assignment,
=, stores that value in the variableresult.
A variable is a named place to store a value. The variable result has type String, which means it holds text.
If you change score to 45 and run the program again, both lines print Try again.
Only one choice is evaluated
The two possible results are often called branches. A branch is one of the paths the program can take.
Java evaluates the condition first. Then it evaluates only the chosen branch. It does not evaluate the other one.
This matters when a branch contains a calculation that is not always safe. Integer division by zero causes an error. The next program avoids that calculation when parts is zero:
public class SafeDivision {
public static void main(String[] args) {
int total = 12;
int parts = 0;
int each = parts != 0 ? total / parts : 0;
System.out.println(each);
}
}The condition parts != 0 is false. Java therefore skips total / parts and uses 0. The program prints:
0The fallback value 0 prevents the error, but it can hide the fact that there were no parts. In a real program, decide whether zero is a useful result or whether an if statement should report the problem instead.
Skipping a branch can also skip a side effect. A side effect is a change or action beyond producing a value, such as changing a variable or printing a message. Avoid putting surprising side effects in branches: they make it harder to see what the program will do.
The result needs a suitable type
A type describes what kind of value an expression can produce. For example, int represents whole numbers, while double can represent numbers with decimal parts.
The branches must produce values that work with the way you use the conditional expression. This program uses a whole number in one branch and a decimal number in the other:
public class ConditionalTypes {
public static void main(String[] args) {
boolean member = true;
double price = member ? 10 : 12.5;
System.out.println(price);
}
}The output is 10.0. In this expression, Java treats the result as a double, even when it selects 10. The variable price can hold that result.
Changing the declaration to int price causes a compile error. A compile error means Java rejects the program before it runs. The possible result 12.5 does not fit in an int.
Grouping the choice
Parentheses show which parts belong together. They are useful when a conditional expression is part of a larger calculation.
In the following program, the first calculation adds 5 to whichever price is chosen. The second adds 5 only in the false branch.
public class ConditionalGrouping {
public static void main(String[] args) {
boolean member = true;
int total = (member ? 80 : 100) + 5;
int differentTotal = member ? 80 : 100 + 5;
System.out.println(total);
System.out.println(differentTotal);
}
}The output is:
85
80For total, the parentheses make the choice first: member is true, so Java selects 80 and then adds 5.
For differentTotal, the + 5 belongs to the false branch, 100 + 5. Since member is true, Java selects 80 and does not use that branch.
Use parentheses when they make your meaning clearer, even if Java would group the expression correctly without them.
Choose between `?:` and `if`
The conditional operator is useful when you need one value or another. For example:
- Choose a label to store in a variable.
- Choose a default number when a calculation is not possible.
- Choose a price based on a condition.
Use if and else when each choice needs several steps, or when the purpose is to perform actions rather than produce one value. A conditional expression should be easy to read at a glance. If it becomes hard to follow, an if statement may be clearer.
You can put a conditional expression inside another one, but several choices in one line can become confusing. Prefer clear code over saving lines.
Practice
Exercise
What value is stored by int points = 55; String label = points >= 60 ? "Pass" : "Try again";?
Show answer
"Try again", because 55 >= 60 is false.
Exercise
In int result = divisor != 0 ? 12 / divisor : 0;, what happens when divisor is zero?
Show answer
The condition is false, so Java skips 12 / divisor and stores 0.
Exercise
If member is false, what does (member ? 80 : 100) + 5 produce?
Show answer
It produces 105: Java selects 100, then adds 5.
Exercise
Why does int price = member ? 10 : 12.5; fail to compile?
Show answer
The conditional expression has type double, and its result cannot be assigned directly to an int.