Java Ternary Operators

  • The operator taking three operands is called ternary operator.
  • It is also called as conditional operator.
  • It is represented as exp1? exp2 : exp3;
  • The mechanism is first the exp1 is evaluated. If the exp1 is true then exp2 will be the output, otherwise exp3 will be the output. Let’s see a program for better understanding.
class ConditionalDemo
{
    public static void main(String[] args)
    {
        int value1 = 1;
        int value2 = 2;
        int result;
        result=(value1>value2) ? value1 : value2 ;
        System.out.println(result);
    }
}

Output

2

Here in above program the expression (value1>value2) is false, so In this example, result will be assigned the value of value2 that is 2. This can be achieved using the if…….else statement as follows :

if(value1>value2)
result=value1;
else
result=value2;

 

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment