Search code examples
javawhile-loop

Java syntax for declaring and initialize variables within a while() loops initialization section?


Can you declare a variable in the while() loops initialization section, in the same way as you can in a for() loop?

Normally, you can write something like this:

boolean continueProgram = true; 
while (continueProgram){
    // Loop program
    continueProgram = false;
}

But i wonder if there is a syntax to write the while() loop the same way as you can do in a for() loop?

A for() loop could look something like this:

for (int i = 0; i < 10; i++){
    // Loop program
}

Is there a way to declare a variable within a while() loop's condition similar to how it's done in a for() loop?

while (boolean continueProgram = true; continueProgram){
    // Loop program
    continueProgram = false;
}

By doing this, the variable would be local to the while() loop only.


Solution

  • No, the syntax of while does not allow this. But you can use a for loop: expressions can be empty too:

    for (boolean continueProgram = true; continueProgram; /* empty */) {
        // Loop program
        continueProgram = false;
    }