Ternary Operators in Java:
The ternary operator (?:) is a shortcut for if-else conditions. It evaluates a boolean expression and returns one of two values based on whether the condition is true or false. It’s called “ternary” because it takes three operands condition, true result, false result.
Syntax:
condition ? expression1 : expression2;
How it Works
- If condition is true → returns expression1
- If condition is false → returns expression2
Example 1: Simple Comparison
class ShikshaSanchar{
public static void main(String[] args){
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println("Maximum: " + max);
}
}
Output:
Maximum: 20
Explanation
- (a > b) is false, so the value after the colon b is assigned to max.
Example 2: Even or Odd
class ShikshaSanchar{
public static void main(String[] args){
int num = 7;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(num + " is " + result);
}
}
Output:
7 is Odd
Explanation
- (num % 2 == 0) is false, so "Odd" is returned and stored in result.
Example 3: Nested Ternary
class ShikshaSanchar{
public static void main(String[] args){
int marks = 75;
String grade = (marks >= 90) ? "A" :
(marks >= 75) ? "B" :
(marks >= 50) ? "C" : "Fail";
System.out.println("Grade: " + grade);
}
}
Output:
Grade: B
Explanation:
- First condition (marks >= 90) is false.
- Second condition (marks >= 75) is true, so "B" is returned.
Notes:
- Used for concise condition checks.
- Can be nested, but avoid too much nesting to keep code readable.
- Can be used in assignment or directly in print statements.
Summary:
- Ternary operator = compact if-else.
- Syntax: condition ? true : false
- Returns value based on the condition.
- Suitable for short, simple decision-making logic.