user3401960
user3401960

Reputation: 1

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?

Upvotes: 0

Views: 60216

Answers (5)

Dr. Collage
Dr. Collage

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

T McKeown
T McKeown

Reputation: 12847

Translated:

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

Upvotes: 2

PeterMmm
PeterMmm

Reputation: 24630

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

Upvotes: 0

Kick
Kick

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

Mena
Mena

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:

  • 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

Upvotes: 11

Related Questions