← Back to Core Java Course | Chapter 3: Operators | Lesson 8 of 9

Java Ternary Operator

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

java
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);
	}
}

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

java
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);
	}
}

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

java
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);
	}
}

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

java
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
	}
}

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

java
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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.