Java Short Hand If...Else (Ternary Operator)
The ternary operator in Java is a shorthand way of writing simple if...else
statements. It can improve code readability and conciseness when dealing with simple conditions.
Key Topics
1. Syntax
The general syntax of the ternary operator is:
variable = (condition) ? expressionTrue : expressionFalse;
2. Example
public class TernaryExample {
public static void main(String[] args) {
int time = 20;
String greeting = (time < 18) ? "Good day." : "Good evening.";
System.out.println(greeting);
}
}
Output:
Good evening.
3. Nested Ternary Operators
You can nest ternary operators, but it may reduce code readability.
public class NestedTernaryExample {
public static void main(String[] args) {
int number = 15;
String result = (number % 2 == 0) ? "Even" : (number % 3 == 0) ? "Divisible by 3" : "Odd";
System.out.println(result);
}
}
Output:
Divisible by 3
Key Takeaways
- The ternary operator is a concise way to perform simple conditional assignments.
- It improves code brevity but can reduce readability if overused or nested.
- Use parentheses to clarify complex expressions when using ternary operators.