What is Ternary Operators in Java?
The ternary operator in Java is a shorthand way of performing a simple if-else condition. It is the only operator in Java that takes three operands, hence the name “ternary.” The syntax of the ternary operator is as follows:
condition ? expression1 : expression2
- condition: A boolean expression that evaluates to either true or false.
- expression1: The value that is returned if the condition is true.
- expression2: The value that is returned if the condition is false.
How It Works #
- If the condition is true, the ternary operator returns the value of expression1.
- If the condition is false, it returns the value of expression2.
Example 1: Basic Usage #
Let’s look at a simple example where we use the ternary operator to determine the larger of two numbers.
public class TernaryOperatorExample {
public static void main(String[] args) {
int a = 10;
int b = 20;
// Using ternary operator to find the larger number
int max = (a > b) ? a : b;
System.out.println("The larger number is " + max);
}
}
Output:
The larger number is 20
In this example, the condition (a > b) evaluates to false, so the ternary operator returns b, which is 20.
Example 2: Assigning a Grade Based on a Score #
The ternary operator can also be used for more complex conditions. For instance, let’s assign a grade based on a student’s score.
public class TernaryOperatorExample {
public static void main(String[] args) {
int score = 85;
// Using ternary operator to assign a grade
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
System.out.println("The grade is " + grade);
}
}
Output:
The grade is B
Here, the ternary operator is nested to evaluate multiple conditions. Since score is 85, the first condition (score >= 90) is false, and the second condition (score >= 80) is true, so the grade assigned is “B”.
Summary #
The ternary operator is a compact way to write simple conditional expressions in Java. It helps in making the code more readable and concise, especially when dealing with simple conditions. However, it should be used with caution in cases where nesting or complex logic might make the code harder to read.