Java Ternary Operator
In this page:
Introduction to Ternary
The ternary operator condenses if (cond) { x = a; } else { x = b; } into one expression, x = cond ? a : b, evaluating the condition and picking the value before or after the colon based on the result.
Example: Introduction to Ternary
public class Main {
public static void main(String[] args) {
int age = 20;
String result = age >= 18 ? "adult" : "minor"; // condenses if/else into one expression
System.out.println(result);
}
}
Login to try C/C++/Java/PHP code in the editor
Setting Values with Ternary
Because the ternary operator itself produces a value, you can assign its result directly to a variable in one line rather than declaring the variable first and filling it in across a separate if-else block.
Example: Setting Values with Ternary
public class Main {
public static void main(String[] args) {
int score = 75;
String grade = score >= 60 ? "Pass" : "Fail"; // assigned directly in one line
System.out.println(grade);
}
}
Login to try C/C++/Java/PHP code in the editor
Nested Ternary Operator
Nesting a ternary inside another, like a ? 1 : (b ? 2 : 3), lets you express three or more branches in a single expression, but each added level makes the line harder to parse at a glance -- most style guides cap nesting at one level.
Example: Nested Ternary Operator
public class Main {
public static void main(String[] args) {
int score = 85;
String grade = score >= 90 ? "A" : (score >= 80 ? "B" : "C"); // three branches in one expression
System.out.println(grade);
}
}
Login to try C/C++/Java/PHP code in the editor
Direct Printing with Ternary
You can embed a ternary expression directly as an argument to println(), producing different printed text based on a condition without writing a separate if-else block just to choose the string.
Example: Direct Printing with Ternary
public class Main {
public static void main(String[] args) {
int stock = 0;
System.out.println(stock > 0 ? "In Stock" : "Out of Stock"); // embedded directly in println
}
}
Login to try C/C++/Java/PHP code in the editor
Ternary vs If-Else
Ternary shines for simple, single-value decisions, but once you need multiple statements or side effects per branch, a full if-else block is clearer and easier to debug than cramming logic into one line.
Example: Ternary vs If-Else
public class Main {
public static void main(String[] args) {
int age = 20;
String label = age >= 18 ? "adult" : "minor"; // simple, single-value: ternary is clear
if (age >= 18) { // multiple statements needed: if-else is clearer here
System.out.println("Granting access");
System.out.println(label);
}
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: