Java Ternary Operator

Ternary Operator

Ternary Operator In Java?

The Java Ternary Operator is a shorthand way to write an if-else statement in a single line.

It takes three operands: a boolean expression, a value to be returned if the boolean expression is true, and a value to be returned if the boolean expression is false.

To understand the more about Java Ternary Operator, Read the Complete Article.

When to use the Ternary Operator?

The ternary operator should be used when you need to assign a value to a variable based on a single condition, and the value assigned to the variable is determined by the outcome of the condition.

It can be useful for simplifying code and reducing the number of lines needed for simple conditional assignments. It should not be used for complex conditions or multiple outcomes, as it can make the code harder to read and understand.

Ternary Operator In Java

Advantages of Java Ternary Operators

Example 1: Java Program for ternary operator in Java 

Run
public class Main {
    //TernaryOperatorExample
    public static void main(String[] args) {
        int num = -5;
        String result = (num > 0) ? "positive" : "negative";
        System.out.println("The number " + num + " is " + result);
    }
}

Output

The number -5 is negative

Example 2: Java Nested Ternary Operator

Run

public class Main {
    //NestedTernaryOperatorExample
    public static void main(String[] args) {
        int num1 = 10;
        int num2 = 20;
        int num3 = 30;
        int max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 : num3);
        System.out.println("The maximum of " + num1 + ", " + num2 + " and " + num3 + " is " + max);
    }
}

Output

The maximum of 10, 20 and 30 is 30

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription