The Java supports the following conditional operators:
|| (conditional OR)
&& (conditional AND)
The conditional operators && and || can be used to perform logical OR or AND operations on boolean operands. The operators are similar to boolean logical operators. The only difference is that if the result is definitely known after evaluating the first operand then second operand is not evaluated as discussed in the previous section. Hence these operators are also known as short-circuit logical operators. Sometimes this proves to be very useful in avoiding run-time exceptions.
For example, the following piece of code may result in a run-time exception, if the value of x is zero (assuming that x and y are integers), as it will lead to division by zero:
x = 0;
if( x != 0 & y/x > 5)
{
----
----
}
The possibility of the run-time exception can be avoided if we use the short-circuit operator && instead of boolean logical operator & as shown below:
x = 0;
if( x != 0 && y/x > 5)
{
----
----
}
|| (conditional OR)
&& (conditional AND)
The conditional operators && and || can be used to perform logical OR or AND operations on boolean operands. The operators are similar to boolean logical operators. The only difference is that if the result is definitely known after evaluating the first operand then second operand is not evaluated as discussed in the previous section. Hence these operators are also known as short-circuit logical operators. Sometimes this proves to be very useful in avoiding run-time exceptions.
For example, the following piece of code may result in a run-time exception, if the value of x is zero (assuming that x and y are integers), as it will lead to division by zero:
x = 0;
if( x != 0 & y/x > 5)
{
----
----
}
The possibility of the run-time exception can be avoided if we use the short-circuit operator && instead of boolean logical operator & as shown below:
x = 0;
if( x != 0 && y/x > 5)
{
----
----
}