Conditional (Ternary) Operator example – Basic java

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.