Reputation: 1
I am not sure if i understand this loop
boolean b = false;
while(!b) {
System.out.println(b);
b = !b;
}
it returns a false, loop is executed once
but does while(!b)
set b= true
? like !b = !false
and b
is printed out?
Upvotes: 0
Views: 60216
Reputation: 87
boolean b = false;
while(!b) { // The !b basically means "continue loop while b is not equal to true"
System.out.println(b);
b = !b; // this line is setting variable b to true. This is why your loop only processes once.
}
Upvotes: 0
Reputation: 12847
Translated:
boolean b = false;
while(b == false) {
System.out.println(b);
b = !b; // b becomes true
}
Upvotes: 2
Reputation: 24630
!
is the negation unary operator in Java a do not modify the operand.
Upvotes: 0
Reputation: 4923
while(!b) { // As b = false but due to ! condition becomes true not b
System.out.println(b); //false will be printed
b = !b; // b = !false i.e. now b is true
}
As now b is true so in next iteration the condition will be false and you will exist from loop
Upvotes: 1
Reputation: 48404
The while (!b)
condition does not set b
to true
.
The b = !b
statement does.
That's why your loop executes only once.
Translation in pseudo-code:
not b
(that is, while b
is false
)b
(so print false
)b
to not b
, that is, the opposite of b
(so assign b
to true
)b
is true
, so not b
condition fails and loop terminatesUpvotes: 11