简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM