I'm doing the oracle certified associate Java SE7 Programmer practice exams (the book) and came across a question, and I don't understand the answer even with the explanation. Here's the explanation and the code:
It will print 3. The loop body is executed twice and the program will print 3.
I don't understand how the loop body is executed twice, maybe I don't understand what the b=!b
means. Can someone explain please?
class TestClass {
public static void main(String args[]){
boolean b = false;
int i = 1;
do{
i + + ;
} while (b = !b);
System.out.println(i);
}
}
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.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 trueAt the end of the first iteration the variable
i
will be2
because of the increment operator. The expressionb=!b
will result totrue
(b = !false
) and set the variableb
totrue
as well. So the loop gets executed again.At the end of the second iteration the variable
i
is now3
. The expressionb=!b
will result tofalse
(b = !true
), which will be also the value of the variableb
. So the whole do-while-loop terminates and theprintln()
statement shows3
.Keep in mind:
=
(assign operator) is not the same as==
(equality check).Iteration 1
Iteration 2
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 likeand you will get the idea.
The condition
uses the assignment operator, which returns the value that has been assigned.
Initially,
b
is false, and thereforetrue
is assigned tob
, and used for the condition. The while loop therefore executes a second time. In this execution,b
is true, and thereforefalse
is assigned tob
and used for the loop condition. The loop therefore exits.