Skip to content

Conditional (Ternary) Operator example – Basic java

  • by

Java ternary operator is the only conditional operator that takes three operands. Java ternary operator is a one-liner replacement for the if-then-else statements.

conditional ternary operator

Syntax

condition ? expr1 : expr2

Description

If condition is true, the operator returns the value of expr1; otherwise, it returns the value of expr2.

Code

public class Hello {
    public static void main(String ar[]) {
        int a = 5;
        int b = 4 ;

        int max = a > b ? a : b;
        System.out.println("Maximum number is : " + max);
    }
}

Output

Maximum number is : 5

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading