Why does the value of "i" not change after executing "boolean t = true,b; b = (t || ((i++) == 0))"

Wyn Wu :
  int i = 0;
  boolean t = true;
  boolean f = false, b;
  b = (t || ((i++) == 0));
  b = (f || ((i+=2) > 0));
  System.out.println(i);

After the above code is executed, the print result is 2, not 3, why?

I find "i" was 0 not 1 after "b = (t || ((i++) == 0))" executed by debuging.Well,I'm confused why "i++" not changes "i".

Jon Skeet :

Well,I'm confused why "i++" not changes "i".

Because i++ doesn't execute in the code you've provided.

In an expression of the form a || b, first a is evaluated, and if it's true (which it is in this case), the expression b isn't evaluated. This is known as short-circuiting.

This is described in JLS section 15.24.

If you change the code to use the non-short-circuited | operator instead, like this:

b = (t | ((i++) == 0));

... then it will evaluate both operands regardless.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=306903&siteId=1