Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explain if (++value % 2 == 0 && ++count < limit) in java

public class AndOperator {

    public static void main(String[] arg) {
        int value = 8;
        int count = 10;
        int limit = 11;

        if (++value % 2 == 0 && ++count < limit) {
            System.out.println("here");
            System.out.println(value);
            System.out.println(count);
        } else{
            System.out.println("there");
            System.out.println(value);
            System.out.println(count);
        }
    }
}

i am getting output as

there
9
10

explain how count is 10....?

like image 770
Sarath Chandra Avatar asked Sep 03 '13 19:09

Sarath Chandra


4 Answers

&& is short-circuit operator. It will only evaluate the 2nd expression if the 1st expression evaluates to true.

Since ++value % 2 == 0 is false, hence it doesn't evaluate the 2nd expression, and thus doesn't increment count.

like image 198
Rohit Jain Avatar answered Oct 17 '22 17:10

Rohit Jain


++value = 9 so ++value % 2 == 0 is false so ++count < limit is not evaluated.

This is called Short circuit evaluation. See the wikipedia page : http://en.wikipedia.org/wiki/Short-circuit_evaluation

like image 42
Pol0nium Avatar answered Oct 17 '22 15:10

Pol0nium


Since you are using &&(logical and) operator.

logical and evaluate second condition only if first condition is evaluated to true

Here in your code first condition ++value % 2 == 0 is evaluated to false,so second condition ++count < limit won't be evaluated.
If you want to execute ++count < limit also use &.
more information read Difference between & and &&

like image 25
Prabhaker A Avatar answered Oct 17 '22 17:10

Prabhaker A


Because ++value % 2 == 0 is false, thus it won't return the first statement. The reason ++value % 2 is false is because value is incremented by one before the mod operator is evaluated. So ++value % 2 is 9 % 2 which != 0.

like image 21
Tyler Iguchi Avatar answered Oct 17 '22 17:10

Tyler Iguchi