Explain about conditional operator with an example.


Conditional Operator in Java

In Java, conditional operators check the condition and decides the desired result on the basis of both conditions. In this section, we will discuss the conditional operator in Java.

Types of Conditional Operator

There are three types of the conditional operator in Java:

  • Conditional AND
  • Conditional OR
  • Ternary Operator
OperatorSymbol
Conditional or Logical AND&&
Conditional or Logical OR||
Ternary Operator?:

Conditional AND

The operator is applied between two Boolean expressions. It is denoted by the two AND operators (&&). It returns true if and only if both expressions are true, else returns false.

Expression1Expression2Expression1 && Expression2
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
TrueTrueTrue

Conditional OR

The operator is applied between two Boolean expressions. It is denoted by the two OR operator (||). It returns true if any of the expression is true, else returns false.

Expression1Expression2Expression1 || Expression2
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse

Let's create a Java program and use the conditional operator.

ConditionalOperatorExample.java

  1. public class ConditionalOperatorExample  
  2. {  
  3. public static void main(String args[])   
  4. {  
  5. int x=5, y=4, z=7;  
  6. System.out.println(x>y && x>z || y<z);  
  7. System.out.println((x<z || y>z) && x<y);  
  8. }  
  9. }  

Output

true
false