5
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....?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61

4 Answers4

15

&& 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.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
4

++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

Pol0nium
  • 1,346
  • 4
  • 15
  • 31
3

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 &&

Community
  • 1
  • 1
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
2

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.

Tyler Iguchi
  • 1,074
  • 8
  • 14