Java Operations · Lesson 5/10
50%
⏱ 10–15 min

Ternary Operator in Java – How It Works and When to Use It

Ternary Operator (or ternary operation) in Java is often used as an alternative to the if-else statement. It consists of three expressions, which is where its name comes from.

General syntax of the ternary operator:

expression1 ? expression2 : expression3

Expression1 represents any expression that evaluates to a boolean value of type boolean.

If expression1 == true, then expression2 is executed; otherwise, expression3 is executed.

Expression2 and expression3 must return values of the same (or compatible) type, which cannot be void.

Example of usage:

public class TernaryOperationExample1 {
    public static void main(String[] args) {
        int i, k;
        i = -10;
        k = i < 0 ? -i : i; // get the absolute value of i
        System.out.print("Absolute value of ");
        System.out.println(i + " is " + k);
    }
}

Java Core

1. Java Introduction
2. Run Your First Java App
3. Java Syntax
4. Java Operations
5. Operators
6. Arrays
7. Sorting Algorithms
8. OOP Basics
9. Lambda Expressions
10. Stream API
11. Inner Classes and Exceptions
12. Git & GitHub
‹ Previous lesson Next lesson ›