Conditional Operators in Java

In Java there are two conditional operators- && (known as Conditional-AND) and || (known as Conditional-OR).

Both Conditional-AND (&&) and Conditional-OR (||) operators in Java perform operations on two boolean expressions and return a boolean value.

Conditional-AND – In case of && operator in Java if any of the two boolean expression is false then the result is false. Following expressions given an idea how conditional-AND operator works in Java.

true && true = true
true && false = false
false && true = false
false && false = false

Conditional-OR– In case of || operator in Java if any of the two boolean expression is true then the result is true. Following expressions given an idea how Conditional-OR operator works in Java.

true || true = true
true || false = true
false || true = true
false || false = false

Java example for conditional operators

Output

short-circuiting behavior with conditional operators

Conditional operators in Java exhibit short-circuiting behavior which means that the second operand in the expression is evaluated only if needed.

In case of && operator if any of the two boolean expression is false then the result is false. Which means if the first expression evaluates to false then there is no need to even evaluate the second expression as the result is anyway going to be false.

In case of || operator if any of the two boolean expression is true then the result is true. Which means if the first expression evaluates to true then there is no need to even evaluate the second expression as the result is anyway going to be true.

Java example exhibiting short-circuiting behavior

Output

As you can see first expression itself evaluates to false that is why method is not even called in the second expression of the conditional-AND.

Output

Now the first expression evaluates to true so the second expression is also evaluated, that is why method is called both of the times now.

To check for short-circuiting behavior in Conditional-OR we can change the expression to || in the above code.

Output

In the if condition, first expression evaluates to true, since its a conditional-or so no need to evaluate second expression as result is anyway going to be true. That is why evaluateMethod() in the second expression is not called.

That’s all for the topic Conditional Operators in Java. If something is missing or you have something to share about the topic please write a comment.


You may also like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.