Powered by Blogger.

How does the ternary Operator Works?

>> Tuesday, November 15, 2011

The Ternary Operator contains three operands with
  "? :". Based on the return type it will give the value.

operand1 ? operand2 : operand3

Ternary Operator Syntax:

boolean expression ? value1 : value2 ;

The first operand is a boolean expression; if the expression is true then the value of the second operand is returned otherwise the value of the third operand is returned:

Here if operand1 is true, operand2 is returned.

operand1 must be a boolean type


Ex:
Boolean isValueBig = ( value > 100  ) ? true : false;

The difference between the ternary operation and if/else is that the ternary expression is a statement that evaluates to a value, while if/else is not.
To use your example, changing from the use of a ternary expression to if/else you could use this statement:
Boolean isValueBig = ( value > 100  ) ? true : false; 
Boolean isValueBig = null; 
 if(  value > 100 ) {
        isValueBig = true;
       } else {
       isValueBig = false;
  }


if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands range, the type of the returned value will be the type of the other operand
short =  true ? short : 1000 // compiles and runs ok
short = false ? short : 1000 // compiles and runs ok 

Example Program:

package com.javabynataraj;
public class Conditional {
   public static void main(String args[]){   
     int a=5;
     int b=10;
     int max;

     max= a > b ? a : b ; 
     System.out.println("Max = "+max);
   }
}

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.