Ternary Operator in Java

In Java, the ternary operator is a type of Java conditional operator. In this section, we will discuss the ternary operator in Java with proper examples.

The meaning of ternary is composed of three parts. The ternary operator (? 🙂 consists of three operands. It is used to evaluate Boolean expressions. The operator decides which value will be assigned to the variable. It is the only conditional operator that accepts three operands. It can be used instead of the if-else statement. It makes the code much more easy, readable, and shorter.

Example.

Ternary Operator in Java

Syntax: 

variable = Expression1 ? Expression2: Expression3

Flowchart

   
      
Ternary Operator Java

Example,

class Ternary {

    public static void main(String[] args)

    {

        // variable declaration

        int n1 = 5, n2 = 10, max;

        System.out.println("First num: "+ n1);

        System.out.println("Second num: "+ n2);

        // Largest among n1 and n2

        max = (n1 > n2) ? n1 : n2;

        // Print the largest number

        System.out.println("Maximum is = "+ max);

    }

}

Reference.

https://www.geeksforgeeks.org/java-ternary-operator-with-examples/

https://www.javatpoint.com/ternary-operator-in-java

https://www.programiz.com/java-programming/ternary-operator

Leave a comment

Design a site like this with WordPress.com
Get started