Ternary
- Java course
- Beginner
- Lesson 40/116
- 4 min
Learn single-line conditionals with ? :.
Ternary
The ternary operator ? : writes a condition in one line. It is used as condition ? trueValue : falseValue.
int score = 75;
String result = (score >= 50) ? "Pass" : "Fail";
System.out.println(result); // PassA ternary produces an expression, so it can be assigned to a variable or passed as an argument. It does the same job as if-else but is shorter. It reads well for simple two-way choices.
When to use ternary
Ternary is ideal for simple two-way assignments. For complex conditions or side effects (assignment, increment) prefer if-else.
// Good: simple choice
String label = (age >= 18) ? "Adult" : "Child";
// Bad: side effect
(score >= 50) ? count++ : count--;Nested ternary is possible but hurts readability. For multiple branches, if-else or switch is better.
Practice Even/odd check
Write a Main class with a main method. Assign 7 to int n. Assign (n % 2 == 0) ? "Even" : "Odd" to String parity. Print parity with println.
Sample solution
public class Main {
public static void main(String[] args) {
int n = 7;
String parity = (n % 2 == 0) ? "Even" : "Odd";
System.out.println(parity);
}
}Expected output
Odd
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ternary
int score = 75;
String result = (score >= 50) ? ____ : "Fail";
int score = 75;
String result = (score >= 50) ? "Pass" : "Fail";
Explanation: When the condition is true, "Pass" is assigned.
2 Match the ternary concepts
| Term | Meaning |
|---|---|
? |
True branch |
: |
False branch |
(x > 0) |
Condition |
"Yes" |
Value |
3 int x = 5; String s = (x > 0) ? "Positive" : "Negative"; — what is s?
- "Positive" Correct answer
- "Negative"
- null
- Error
Explanation: x > 0 is true, so "Positive" is assigned.