The ternary operator in Java is a shorthand way to write simple if-else conditions in a single line. It makes code shorter, cleaner, and easier to read when used correctly.
? and : symbolsThe ternary operator evaluates a condition and returns one of two values.
Syntax
// General syntax of ternary operator
result = (condition) ? valueIfTrue : valueIfFalse;
// Check which number is greater using ternary operator
int a = 10;
int b = 20;
int max = (a > b) ? a : b;
System.out.println(max);
20
The condition a > b is false, so the value of b is assigned to max.
if-else for complex logic