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

Author: Tatyana Milkina

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 для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments