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
Operator | Symbol |
---|---|
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.
Expression1 | Expression2 | Expression1 && Expression2 |
---|---|---|
True | False | False |
False | True | False |
False | False | False |
True | True | True |
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.
Expression1 | Expression2 | Expression1 || Expression2 |
---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
Let's create a Java program and use the conditional operator.
ConditionalOperatorExample.java
Output
true false