0Pricing
Java Academy · Lesson

The Ternary Operator

condition ? a : b.

The Ternary Operator is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

What Is the Ternary Operator?

The ternary operator is Java's only operator that takes three operands. It is a compact way to choose between two values based on a condition.

Its shape is: condition ? valueIfTrue : valueIfFalse.

It produces a value, so you can assign it or pass it directly.

int age = 20;
String status = age >= 18 ? "adult" : "minor";

The Three Parts

The first part is a boolean condition. The ? separates it from the results.

If the condition is true, the expression evaluates to the part before :. If false, it evaluates to the part after :.

Only one of the two branches is actually evaluated.

int score = 45;
String result = score >= 50 ? "pass" : "fail";

A Full Running Example

Here is a complete program that prints a label based on a number.

The condition n % 2 == 0 decides whether to use "even" or "odd".

public class Main {
    public static void main(String[] args) {
        int n = 7;
        String parity = n % 2 == 0 ? "even" : "odd";
        System.out.println(parity);
    }
}

It Is an Expression

Unlike an if statement, a ternary is an expression: it has a value.

That means you can use it inside method calls, returns, and assignments where a statement would not fit.

public class Main {
    public static void main(String[] args) {
        int a = 9, b = 4;
        System.out.println("Max is " + (a > b ? a : b));
    }
}

Choosing Numbers

Both branches do not have to be strings. Here the ternary picks the larger of two ints.

The result is an int you can store and reuse.

public class Main {
    public static void main(String[] args) {
        int x = 12, y = 30;
        int max = x > y ? x : y;
        System.out.println(max);
    }
}

Both Branches Must Have Compatible Types

Java needs to know the type of the whole expression, so the two branches must have compatible types.

If one branch is an int and the other a String, the code will not compile.

Keep both sides the same kind of value.

boolean ok = true;
// valid: both ints
int code = ok ? 200 : 404;
// invalid: int vs String would not compile

Returning from a Method

Ternaries shine inside return statements, replacing a four-line if/else with one line.

The method below returns the absolute value of a number.

public class Main {
    static int abs(int n) {
        return n < 0 ? -n : n;
    }
    public static void main(String[] args) {
        System.out.println(abs(-8));
    }
}

Using It in Output

You can embed a ternary directly inside a print call.

Wrap it in parentheses when concatenating, so the ? and : are grouped before the + joins the text.

public class Main {
    public static void main(String[] args) {
        int items = 0;
        System.out.println("Cart: " + (items == 0 ? "empty" : "has items"));
    }
}

Picking a Greeting

A common use is selecting one of two messages.

The condition checks a boolean flag, and the ternary chooses the matching greeting text.

public class Main {
    public static void main(String[] args) {
        boolean morning = true;
        String greet = morning ? "Good morning" : "Hello";
        System.out.println(greet);
    }
}

Operator Precedence

The ternary has very low precedence, so arithmetic and comparisons inside it run first.

In a + b > 10 ? "big" : "small", Java computes a + b, compares it, then picks a branch.

Add parentheses when mixing with + for string concatenation.

int a = 6, b = 7;
String size = a + b > 10 ? "big" : "small";

Assigning Based on Input

Ternaries are great for initializing a variable in one step.

Here a fee is set to zero for members and a flat amount otherwise.

public class Main {
    public static void main(String[] args) {
        boolean isMember = false;
        double fee = isMember ? 0.0 : 9.99;
        System.out.println(fee);
    }
}

Quick Check

Test your understanding of ternary syntax.

Recap

The ternary operator condition ? a : b is Java's compact, three-part conditional expression.

It returns a value, only evaluates one branch, and needs compatible types on both sides.

Use it to assign, return, or print one of two values cleanly.

Frequently asked questions

Is the “The Ternary Operator” lesson free?

Yes — the full text of “The Ternary Operator” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “The Ternary Operator”?

condition ? a : b. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “The Ternary Operator” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Ternary Operator
  2. Nesting Ternaries
  3. Ternary vs if/else
  4. Readability Pitfalls
← Back to Java Academy