The Ternary Conditional Operator ? : in Java
In this article, we will explore the ternary operator ?(question mark) and :(colon) in Java, what is its purpose, and why do we use it?
1. What is a Ternary Operator?
The operator ? : in Java, is a ternary operator. It uses to evaluate a boolean expression. It is also known as a conditional operator. It consists of three operands separated by two operators: question mark (?) and colon(:). Its structure is as below:
z = (boolean expression to evaluate) ? (value assign to 'z' if true) : (value assign to 'z' if false)
In above example, parenthesis are optional.
2. Why we use it?
It is much similar to the if-else statement. However, the goal of the ternary operator is to evaluate the expression and decide which one of the values assign in a variable. Unlike the if-else statement, where a block of code spreads over several lines, it is one line statement.
3. Examples using the ternary operator in Java
public class TernaryOperatorBooleanTest { public static void main(String[] args) { int totalMangoes = 6; // ternary operator example boolean isDozen = totalMangoes == 12 ? true : false; System.out.println("Mangoes count is dozen:"+isDozen); } }
In the preceding code, totalMangoes
is set as 6, then isDozen
value is assigned by evaluating the condition totalMangoes == 12
, if the total mangoes are equals to 12 then isDozen
is set as true otherwise false.
public class TernaryOperatorStringTest { public static void main(String[] args) { int month = 6; // ternary operator example String season = (month >= 4 && month <=10) ? "summer" : "winter"; System.out.println("month is in season:"+season); } }
In the above example, boolean expression enclosed in parenthesis makes compound expression means both expressions should evaluate to get a final boolean value and set value in season
accordingly.
You can also check the Ternary Operator Java Example.
4. Download the Source Code
This is an example of the ternary operator ? : in Java.
You can download the full source code of ternary operators from here: The Ternary Conditional Operators: ? in Java
The first example is poor as it is simpler to write boolean isDozen = totalMangoes == 12;
Is the value of the second operand always ‘true’ and the third operand always ‘false’ even if they are strings ?