0

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?

1
  • 1
    No, b = !b does that. It inverts b. Commented Mar 10, 2014 at 14:26

5 Answers 5

11

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
Sign up to request clarification or add additional context in comments.

Comments

2

Translated:

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

Comments

1
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

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.