Java's while are similar to the for loops. Java while enables your programs to repeat a set of operations while a certain conditions is true.
Here is a simple example:
int counter = 0;

while(counter < 10) {

    System.out.println("counter: " + counter);

    counter++;
}
This example shows a while loop that executes the body of the loop as long as the countervariable is less than 10. Inside the loop body the counter is incremented. Eventually the countervariable will no longer be less than 10, and the while loop will stop executing.
Here is another example that uses a boolean to make the comparison:
boolean shouldContinue = true;

while(shouldContinue == true) {

    System.out.println("running");

    double random = Math.random() * 10D;

    if(random > 5) {
        shouldContinue = true;
    } else {
        shouldContinue = false;
    }

}
This example tests the boolean variable shouldContinue to check if the while loop should be executed or not. If the shouldContinue variable has the value true, the while loop body is executed one more time. If the shouldContinue variable has the value false, the while loop stops, and execution continues at the next statement after the while loop.
Inside the loop body a random number between 0 and 10 is generated. If the random number is larger than 5, then the shouldContinue variable will be set to true. If the random number is 5 or less, the shouldContinue variable will be set to false.
Like with for loops, the curly braces are optional around the loop body. If you omit the curly braces then the loop body will consist of only the first following Java statement. Here is an example:
while(iterator.hasNext())
  System.out.println("next: " + iterator.next()); // executed in loop
  System.out.println("second line");              // executed outside loop
In this example, only the first System.out.println() statement is executed inside the whileloop. The second System.out.println() statement is not executed until after the while loop is finished.
Forgetting the curly braces around the while loop body is a common mistake. Therefore it can be a good habit to just always put them around the while loop body.

Powered by Blogger.

- Copyright © 2013 Taqi Shah Blogspot -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -