Understanding do-while loop

雨燕双飞 提交于 2019-12-02 01:06:01

b = !b is an assignment which assigns the inverse of b to itself (effectively flipping between true and false)

in java, an assignment returns what was assigned (so that a=b=1 is possible)

therefore while (b=!b) will flip the value of b, and then check the value of b.

b=!b

Will always be true, why? Because, what you are doing is that you insert to "b" the opposite value (T->F, F->T),and if there was no problem while (b = !b); will return TRUE....
So at your case while (b = !b); will always return true

Iteration 1

boolean b = false; 
int i = 1; 
do{ 
    i++ ; // i = 2
} while (b = !b); // b = !false = true so one more execution

Iteration 2

do{ 
    i++ ; // i = 3
} while (b = !b); // b = !true = false so loop breaks

So it will print 3. simple :)

Actually the confusion is with = sign. = is assigning operator where as == is the conditional operator. The first will assign the value whereas later will check for the condition. You can play with it and have some other result like

int a = 6;
int b = 10;
System.out.println(a = b);
System.out.println(a == b);

and you will get the idea.

At the end of the first iteration the variable i will be 2 because of the increment operator. The expression b=!b will result to true (b = !false) and set the variable b to true as well. So the loop gets executed again.

At the end of the second iteration the variable i is now 3. The expression b=!b will result to false (b = !true), which will be also the value of the variable b. So the whole do-while-loop terminates and the println() statement shows 3.

Keep in mind: = (assign operator) is not the same as == (equality check).

The condition

b = !b;

uses the assignment operator, which returns the value that has been assigned.

Initially, b is false, and therefore true is assigned to b, and used for the condition. The while loop therefore executes a second time. In this execution, b is true, and therefore false is assigned to b and used for the loop condition. The loop therefore exits.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!