Program of Ternary operator in java


In ternary operator use three operands.It is also called conditional assignment statement because the value assigned to a variable depends upon a logical expression.

syntax is :

variable=(test expression) ? Expression 1 : Expression 2

 

 

 

 

 

 

 

 

 

 

Output:-


 

 

 

 

Nested Conditional operator:

we can use conditional operator(ternary operator) in nested form as shown below:

Program to find maximum among three numbers:

int  a=15,  b=22,  c=13 ;

max =   (a>b) ?                       (a>c) ? a : c         : (b>c) ? b : c ;

Test condition           Expression 1          Expression 2

The test condition a>b is false. Hence it will operate expression 2.in expression 2,the test condition b>c is true which enables value 12 to be stored in max. Hence  max=22

Related Posts

Comments are closed.