Ternary Operator

Conditional operator (?:)

Interview Relevant: Concise conditional expressions
4 min read

The Ternary Operator (?:)

The ternary operator is Java's only operator that takes three operands. It provides a shorthand way to write simple if-else statements.

Syntax

result = condition ? valueIfTrue : valueIfFalse;

āœ“ Benefits: Concise one-liners for simple conditions, can be used inline in expressions, great for assignments and return statements.

How It Works

  • condition is evaluated first
  • If true, valueIfTrue is returned
  • If false, valueIfFalse is returned
  • Only ONE of the values is evaluated (short-circuit)

āš ļø Warning: Don't nest ternary operators deeply! a ? b ? c : d : e ? f : g is unreadable. Use if-else instead.

Code Examples

Basic ternary operator usage

java
1// Basic usage
2int age = 20;
3String status = age >= 18 ? "Adult" : "Minor";
4System.out.println(status);  // Adult
5
6// Equivalent if-else
7String status2;
8if (age >= 18) {
9    status2 = "Adult";
10} else {
11    status2 = "Minor";
12}
13
14// Finding max of two numbers
15int a = 10, b = 20;
16int max = a > b ? a : b;
17System.out.println("Max: " + max);  // 20

Ternary in expressions and methods

java
1// Inline in expressions
2int score = 85;
3System.out.println("Grade: " + (score >= 90 ? "A" : score >= 80 ? "B" : "C"));
4
5// In method arguments
6int value = -5;
7System.out.println(Math.abs(value > 0 ? value : -value));
8
9// With method calls
10String name = null;
11String display = name != null ? name.toUpperCase() : "UNKNOWN";
12System.out.println(display);  // UNKNOWN
13
14// Return statement
15public static String getStatus(boolean isActive) {
16    return isActive ? "Active" : "Inactive";
17}

Nested ternary and type rules

java
1// Nested ternary (use sparingly!)
2int num = 0;
3String sign = num > 0 ? "Positive" 
4            : num < 0 ? "Negative" 
5            : "Zero";
6System.out.println(sign);  // Zero
7
8// Better: Use if-else for complex conditions
9String sign2;
10if (num > 0) {
11    sign2 = "Positive";
12} else if (num < 0) {
13    sign2 = "Negative";
14} else {
15    sign2 = "Zero";
16}
17
18// Type compatibility
19int x = 5;
20// Both branches must return compatible types
21double result = x > 0 ? 1.5 : 2;  // 2 is promoted to 2.0

Practical real-world examples

java
1// Practical examples
2
3// Null-safe default value
4String input = null;
5String value = input != null ? input : "default";
6
7// Even/Odd check
8int n = 7;
9System.out.println(n + " is " + (n % 2 == 0 ? "even" : "odd"));
10
11// Pluralization
12int count = 1;
13System.out.println(count + " item" + (count != 1 ? "s" : ""));
14
15// Min of three numbers
16int a = 5, b = 3, c = 8;
17int min = a < b ? (a < c ? a : c) : (b < c ? b : c);
18System.out.println("Min: " + min);  // 3
19
20// Boolean to Yes/No
21boolean flag = true;
22String yesNo = flag ? "Yes" : "No";

Use Cases

  • Simple value assignment based on condition
  • Inline conditional expressions
  • Default value assignment
  • Pluralization in output
  • Compact return statements
  • Null-safe value handling

Common Mistakes to Avoid

  • Nesting ternary operators too deeply
  • Using for complex logic (use if-else instead)
  • Forgetting that both branches must return compatible types
  • Not using parentheses for clarity in complex expressions
  • Using ternary with side effects (hard to read)
  • Returning void expressions (not allowed)