Ternary Operator in Java with Examples: Ternary Operator vs. if...else Statement
The ternary operator is Java's only conditional operator that takes three operands, making it a compact shorthand for simple if...else logic. It's written using ? and :.
Syntax
variable = (condition) ? valueIfTrue : valueIfFalse;
Basic Example
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(status); // Adult
Equivalent if...else Statement
int age = 20;
String status;
if (age >= 18) {
status = "Adult";
} else {
status = "Minor";
}
System.out.println(status);
Ternary Operator vs if...else Statement
- The ternary operator is an expression that returns a value;
if...elseis a statement that controls program flow - Ternary is best for short, simple conditions assigned to a variable;
if...elseis better for multiple statements or complex logic - Ternary expressions can be nested, but doing so often hurts readability compared to a clear
if...elsechain - Both evaluate the same condition logic — the choice mainly comes down to code clarity and use case
Nested Ternary Example
int marks = 75;
String grade = (marks >= 90) ? "A" : (marks >= 75) ? "B" : "C";
Use the ternary operator for quick, single-value decisions, but switch to
if...else once your logic involves multiple conditions or actions, since deeply nested ternaries become hard to read.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.