top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Why does Java still offer the normal AND and OR operators ?

+1 vote
442 views
Why does Java still offer the normal AND and OR operators ?
posted Jan 22, 2016 by Nway Nadar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

In some cases you will want both operands of an AND or OR operation to be evaluated because of the side effects produced.

Consider the following:

// Side effects can be important.
class SideEffects {
public static void main(String args[]) {
int i;
i = 0;

/* Here, i is still incremented even though the if statement fails. */
if(false & (++i < 100))
System.out.println("this won't be displayed");
System.out.println("if statements executed: " + i);                                // displays 1 2

/* In this case, i is not incremented because the short-circuit operator skips the increment. */
if(false && (++i < 100))
System.out.println("this won't be displayed");
System.out.println("if statements executed: " + i);                                // still 1 !!
}
}

As the comments indicate, in the first if statement, i is incremented whether the if succeeds or not. However, when the short-circuit operator is used, the variable i is not incremented when the first operand is false. The lesson here is that if your code expects the right-hand operand of an AND or OR operation to be evaluated, you must use Java’s non-short-circuit forms of these operations.

answer Jan 22, 2016 by Reshmi S
...