The java ternary operators is a concise way to perform conditional expressions. It is often referred to as the conditional operator and is represented by ? :
. This operator can make your code cleaner and more readable when used appropriately.
The ternary operator is a shorthand for an if-else
statement. It takes three operands, hence the name “ternary.” The syntax is as follows:
Let’s dissect the syntax further with an example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
In this case:
(a > b)
evaluates to false
(since 10 is not greater than 20).?
, which is a
, will not be executed.:
, which is b
, will be executed.max
will be assigned the value of 20
.if-else
statement.The ternary operators is best suited for simple conditional assignments. It’s generally recommended to avoid complex expressions or multiple nested ternary operations, as they can reduce code readability and increase the risk of bugs.
Let’s start with a straightforward example of using the ternary operator:
public class TernaryExample {
public static void main(String[] args) {
int age = 20;
String eligibility = (age >= 18) ? "Eligible to vote" : "Not eligible to vote";
System.out.println(eligibility);
}
}
//output
Eligible to vote
In this example, we check if the variable age
is 18 or older. If true, eligibility
is assigned “Eligible to vote”; otherwise, it gets “Not eligible to vote”.
You can chain multiple ternary operators, but it’s crucial to ensure clarity:
public class TernaryMultipleExample {
public static void main(String[] args) {
int score = 75;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" : "D";
System.out.println("Grade: " + grade);
}
}
//output
Grade: C
Here, we assign grades based on the score
. Each condition is checked in sequence until one evaluates to true. This example illustrates the potential for readability issues when using chained ternary operators.
The ternary operator can also be used in conjunction with method calls, which can simplify your code:
public class TernaryMethodExample {
public static void main(String[] args) {
int a = 5, b = 10;
String result = (a < b) ? getLowerValue(a, b) : getHigherValue(a, b);
System.out.println("Result: " + result);
}
public static String getLowerValue(int x, int y) {
return x + " is lower than " + y;
}
public static String getHigherValue(int x, int y) {
return x + " is higher than " + y;
}
}
//output
Result: 5 is lower than 10
In this example, we determine whether a
is less than b
. Based on the condition, we call one of two methods to get a message.
The ternary operator can also be effectively utilized when initializing arrays or collections:
import java.util.Arrays;
public class TernaryArrayExample {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int threshold = 3;
String[] results = Arrays.stream(numbers)
.mapToObj(num -> (num > threshold) ? "Above" : "Below")
.toArray(String[]::new);
System.out.println(Arrays.toString(results));
}
}
//output
[Below, Below, Below, Above, Above]