Ternary Operator



? operator is ternary operator, because of number of operands it works on are three.


Syntax:


<condition> ? <statement 1> : <statement 2> ;

In ternary operator if condition is evaluated true then statement 1 will get executed otherwise statement 2 will be executed.

Example:

	 //file:ter.java
	 //www.jgyan.com
class ter
 {
  public static void main(String arg[])
   {
     int a=10,b=20;
	 (a<b)? System.out.println("a is less than"): System.out.println("b is less than");
   }
 }
 /* Output:
 a is less than
 */
 



Ternary operator can be used with assignment operator also.


Syntax:

var = <condition> ? <statement 1> : <statement 2> ;

In ternary operator if condition is evaluated true then statement 1 will get executed otherwise statement 2 will be executed.

	 //file:ter1.java
	 //www.jgyan.com
class ter1
 {
  public static void main(String arg[])
   {
     int a=10,b=20;
	 int min = (a < b) ? a:b;
	 System.out.println("Minimum is :"+min);
   }
 }
 /* Output:
 Minimum is 10
 */