Java while loop boolean evaluation

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?

Answers


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:

  • while not b (that is, while b is false)
  • print b (so print false)
  • assign b to not b, that is, the opposite of b (so assign b to true)
  • next iteration of the loop, b is true, so not b condition fails and loop terminates

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


Translated:

 boolean b = false;
 while(b == false) {
 System.out.println(b);
 b = !b;  // b becomes true
}

! is the negation unary operator in Java a do not modify the operand.


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

Need Your Help

GPUImagePicture with a GPUImageBuffer target?

ios objective-c gpuimage

I'm trying to do the following to display an image instead of trying to access video when TARGET_IPHONE_SIMULATOR is true.