Ternary Operator
The ternary operator is a shortcut for a simple if-else decision, written in a single line. It's called "ternary" because it works with three parts: a condition, a result if true, and a result if false.
1. What is the Ternary Operator?
The ternary operator is a shortcut for a simple if-else decision, written in a single line. It's called "ternary" because it works with three parts: a condition, a result if true, and a result if false.
2. Why is it used?
It makes code shorter and cleaner for simple two-outcome decisions, avoiding a full if-else block when only one value needs to be picked based on a condition.
3. Real-Life Example
Think of a quick decision: "If it's raining, take an umbrella; otherwise, don't." This whole sentence can be captured in a single compact line using the ternary operator, instead of writing separate if and else blocks.
4. Syntax
javaresult = (condition) ? valueIfTrue : valueIfFalse;
5. Example Program
javapublic class TernaryDemo { public static void main(String[] args) { int marks = 40; String result = (marks >= 35) ? "Pass" : "Fail"; System.out.println("Result: " + result); } }
Output:
Result: Pass6. Key Points to Remember
- The ternary operator always returns a value — it's an expression, not just a statement.
- Best used for simple, single-decision cases; complex conditions are clearer with a full if-else.
- Ternary operators can be nested, but this quickly becomes hard to read and should be avoided in real projects.