Ternary Operator in Java
Conditional statements are used to check whether a condition is true or false and decide the next step according to the outcome. Ternary operator in Java is used to replace conditional statements. They are called so because they operator on three operands. They provide a cleaner and more readable code, and we can write if-else logic in a single line of code. Let's learn how to use ternary operators in Java.
The ternary operator uses the question mark(?) and the colon(:) to separate the condition and the expressions that will be evaluated according to the outcome of the condition. The general syntax of the ternary operator is shown below.
If the condition evaluates to true, then the expression1 will be executed, else expression2 will be executed. The above logic can be written using if-else statements as shown below.
if(condition)
variable = expression1;
else
variable = expression2;
One thing to note here is that the expressions must return a value. We cannot use a method that returns a void. Consider the following if-else code.
public static void main(String args[])
{
if (10 > 5)
System.out.print("True");
else
System.out.print("False");
}
True
We cannot use ternary operators to do the same thing. The following code written using ternary operators will return an error.
public static void main(String args[])
{
(10 > 5) ? System.out.print("True"): System.out.print("False");
}
Example: Ternary Operator in Java
Let's have two variables one of int data type and the other one is of String data type. If the integer is equal to 10 then the string should have the value ten, else it should have the value not ten.
The Java code using the ternary operator can be written as shown below.
public static void main(String args[])
{
int i = 11;
String s;
s = (i == 10) ? "ten" : "not ten";
System.out.print(s);
}
not ten
Example: Nested Ternary Operator in Java
Like nested if-else, the ternary operator can be nested. Here, we are trying to find the grade of a student based on his marks. If he scores greater than 90, then the grade is A, if marks are between 50 and 90 then the grade is B, otherwise, the grade is C.
The following Java code is implementing the nesting Ternary operator.
public static void main(String args[])
{
int marks = 65;
char grade;
grade = (marks >= 90) ? 'A' : (marks < 90 && marks >= 50) ? 'B' : 'C';
System.out.print(grade);
}
B
For better readability, we can also write the above code in the following format.
public static void main(String args[])
{
int marks = 65;
char grade;
grade = (marks >= 90) ? 'A'
:(marks < 90 && marks >= 50) ? 'B'
:'C';
System.out.print(grade);
}
B
Summary
The ternary operator is used to write if-else conditional statements in a single line. They can make our code cleaner and also make it easy to understand. However, for nested if-else statements, and if-else if-else statements, ternary operators can be difficult to comprehend. They should mostly be used to replace simple if-else statements.