Java Ternary Operator: Simplifying If...Else Statements

Learn about the ternary operator in Java, a shorthand version of the if...else statement that uses three operands for concise conditional expressions. This powerful operator allows you to replace simple if...else constructs with a single line of code, improving readability and efficiency. Discover how to utilize the ternary operator to streamline your code and simplify decision-making processes in your Java applications.



Short Hand if...else (Ternary Operator)

There is a short-hand if...else statement in Java, known as the ternary operator because it consists of three operands. It can be used to replace simple if...else statements with a single line of code:

variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}

You can simply write:

int time = 20;
String result = (time < 18) ? "Good day." : "Good evening.";
System.out.println(result);

Explanation: In the example above, time (20) is greater than 18, so the condition time < 18 is false. Therefore, the ternary operator evaluates to "Good evening." and assigns this value to the variable result, which is then printed to the console.