Java Ternary Operator Example

This Java example demonstrates how to use the ternary operator (?:) in Java with an example.

Java Ternary Operator 

Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements.
Syntax:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the expression evaluated.

Java Ternary Operator Example

Here is a program that demonstrates the ? operator. It uses it to obtain the absolute value of a variable.
package net.javaguides.corejava.operators.ternary;

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



Comments