Scope of do-while loop?

In your example, the boolean variable b is scoped to the body of the do..while loop. Since the conditional check is executed outside the body, the variable is out of scope. The correct construct would be:

boolean b = false ; // Or whichever initial value you want
do {
    b = false;
} while (b);

You can write something like this if you want exit do-while block while boolean defined inside of do-while block.

do{
  boolean b;
  ...
  if(b){
    break;
  }
}while(otherCondition)  //or while(true)

Because that's one way scope is defined in Java; inside {} is a new scope.

IMO it wouldn't make much sense to special-case a single construct.


Following your logic here is the case when b would not be defined prior to first usage:

do {
    continue;
    boolean b = false;
} while (b); // b cannot be resolved to a variable

Note that very often boolean flags are a code smell, try to avoid them rather than fight with them.

Tags:

Java

Scope