What is Java Ternary Operator(?:)
Definition
The question mark operator (? :
) is a conditional operator that selects one of two expressions based on the evaluation result of a condition. It can achieve results similar to an if statement.
Structure
if (Condition) {
result = expression1;
} else {
result = expression2;
}
result = Condition ? expression1 : expression2;
It is equivalent to an if statement.
Considerations for Use
When using the ternary operator, the following considerations should be taken into account:
Advantages
Code Conciseness: It allows expressing logic where a value is chosen based on a condition in a single line, enhancing code readability and conciseness.
Expression Reusability: The selected expression can be assigned to a variable or used as part of other expressions, thus increasing reusability.
Disadvantages
- Readability of Complex Conditions: While the ternary operator is suitable for simple conditions, it may reduce readability for complex condition expressions. In such cases, using if-else statements might be more appropriate.
Step-by-Step Usage
Write the condition expression. The condition expression should evaluate to a boolean value (true or false).
Follow the condition expression with a question mark (
?
).Write the expression to be selected if the condition is true, followed by a colon (
:
).Write the expression to be selected if the condition is false.
The result of the ternary operator is the value of the selected expression.
Example
int age = 18;
String message = (age >= 18) ? "You are an adult." : "You are a minor.";
System.out.println(message); // Output: "You are an adult."
In the example above, the value of the age
variable is 18 or older, so the condition (age >= 18)
evaluates to true. Therefore, the expression1
, "You are an adult.", is selected and assigned to the message
variable.