Conditional (Ternary) Operator in Java
☰Fullscreen
Table of Content:
Below is a simple, clear, student-friendly tutorial on the Conditional Operator in Java, perfect for teaching and also for your website / YouTube audience.
✅ Conditional (Ternary) Operator in Java – Easy Tutorial
In Java, the conditional operator is also known as the ternary operator.
It is the shortest way to write an if-else statement.
1. Syntax
condition ? expression1 : expression2;
✔ How it works?
-
If condition is true → expression1 runs
-
If condition is false → expression2 runs
That’s it!
2. Example 1: Check if a number is even or odd
int num = 10;
String result = (num % 2 == 0) ? "Even" : "Odd";
System.out.println(result);
✔ Output:
Even
3. Example 2: Find the largest of two numbers
int a = 30;
int b = 20;
int max = (a > b) ? a : b;
System.out.println("Largest = " + max);
✔ Output:
Largest = 30
4. Example 3: Assign pass/fail depending on marks
int marks = 75;
String status = (marks >= 40) ? "Pass" : "Fail";
System.out.println(status);
✔ Output:
Pass
5. Example 4: Nested Ternary Operator (3-way comparison)
int n = 0;
String type = (n > 0) ? "Positive" : (n < 0) ? "Negative" : "Zero";
System.out.println(type);
✔ Output:
Zero
6. Example 5: Shorter replacement of if-else
Traditional if-else:
if(age >= 18) {
message = "Eligible to Vote";
} else {
message = "Not Eligible";
}
Using conditional operator:
message = (age >= 18) ? "Eligible to Vote" : "Not Eligible";
7. Why use the Conditional Operator?
| Reason | Explanation |
|---|---|
| ✔ Short code | Replaces 3–4 lines with one line |
| ✔ Better readability | Good for simple decisions |
| ✔ Faster writing | Saves time in assignments/exams |
8. When NOT to use it?
Don’t use ternary operator when the logic is complex.
Use it only for simple one-line decisions.
📌 Summary
-
Conditional Operator =
? : -
Quick replacement of if-else
-
Good for small checks
-
Avoid in complicated logic