The && and || operators are short-circuit operators. These operators exhibit "short-circuiting" behavior, which means that the second operand is evaluated only if needed.
Case A1
int x = 0;
if(5/x == 0 || x == 0)
{
System.out.println("Ok");
}
else
{
System.out.println("Sure");
}
Case A1 will cause an ArithmeticException: / by zero error.
Case A2
int x = 0;
if(x == 0 || 5/x == 0)
{
System.out.println("Ok");
}
else
{
System.out.println("Sure");
}
Case A2 will print "OK" because once x == 0 is true. Java will not continue to evaluate the second part.
Case B1
int x = 0;
if( x == 0 && 5/x == 0)
{
System.out.println("Ok");
}
else
{
System.out.println("Sure");
}
Case B1 will cause an ArithmeticException: / by zero error.
Case B2
int x = 0;
if(x != 0 && 5/x == 0)
{
System.out.println("Ok");
}
else
{
System.out.println("Sure");
}
Case B2 will print "Sure" because once x != 0 is false. Java will not continue to evaluate the second part.