Careeroza
Ternary Operator
Short if...else
The ternary operator condition ? valueIfTrue : valueIfFalse picks one of two values. It is an expression, so it returns a value you can store or print.
Example
public class Main {
public static void main(String[] args) {
int stock = 0;
String label = stock > 0 ? "In stock" : "Out of stock";
System.out.println(label);
int a = 14, b = 9;
int bigger = a > b ? a : b;
System.out.println("Bigger: " + bigger);
int items = 1;
System.out.println(items + (items == 1 ? " item" : " items"));
}
}Output
Out of stock Bigger: 14 1 item
When to Use It
- Good for choosing between two simple values.
- Avoid nesting ternaries (
a ? b : c ? d : e); use if/else instead. - Both result values must be compatible types.
Exercise: Using a ternary, store "Even" or "Odd" in String type for int n.
Show answer
String type = n % 2 == 0 ? "Even" : "Odd";