Conditional or Ternary Operators in Java


The conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. When using a Java ternary construct, only one of the right-hand side expressions, i.e. either expression1 or expression2, is evaluated at runtime.Condition? expression1: expression2;

• if condition is true, expression1 is executed.
• And, if condition is false, expression2 is executed.
The ternary operator takes 3 operands (condition, expression1, and expression2). Hence, the name ternary operator.

Source Code

public class Conditional {
    public static void main(String args[])
    {
      //Conditional or Ternary Operators in Java  ?:
        int a=45,b=35,c;
        c=a>b?a:b;
        System.out.println("The Greatest Number is : "+c);
 
    }
}
 

Output

The Greatest Number is : 45
To download raw file Click Here

Basic Programs