ADS

Ternary Operator Example In Java

The following illustrates an example of ternary operator in Java. The ternary operator is ?: which acts like an if-else ladder. It is simple a short form.

A bit about the Ternary operator..

The ternary operator is ?: This operator as said before works like if-else. If the condition is true then you can store a particular value in the variable if false some other value can be stored. An example will make you understand it clear.

 boolean myFlag= (isTrue==true?  true: false);

The syntax is,

 value=(expression? value1:value2);

value1 and value2 both should be of the same value type. In this case, if expression (condition) is satisfied then value1 is stored in value else value2 is stored. The above statement is much similar to.

 if(expression){value=value1;}
else {value=value2;}

I think you might have understood it. So let's walk into the example.

 import java.util.*;
class TernaryOperatorExample
{
    public static void main(String args[])
    {
    Scanner s=new Scanner(System.in);
    int n=s.nextInt();

    String st=(n>0? n+">0":n+"<0");

    System.out.println(st);
    }
}

Sample Output

 8
8>0

Explanation

User gives an int value and that is stored in n.
Next, if n>0, then the value of st will become n+">0". Consider if n=8, then st will become 8>0
Else if n<0, then the value of st will become n+"<0". If n=-8, then st will become -8<0. As the user gave 8 is input, this statement is not reached.

Subscribe to receive free email updates:

ADS