Java Language Tutorial
Java Introduction
What is Java?
Java Core Concepts
Java Syntax
 
Java Variables
Java Data Types
Java Strings
Java Operations
   Java if
   Java switch
   Java for
   Java while
Java Classes
Java Fields
Java Methods
Java Constructors
Java Packages
Java Access Modifiers
Java Inheritance
Java Nested Classes
Java Abstract Classes
Java Interfaces
Java Interfaces vs.
Abstract Classes
Java Enums
Java Annotations
 
Java Main Program
 


Java while Loops

Connect with me:  
  Jenkov.com - News

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 counter variable is less than 10. Inside the loop body the counter is incremented. Eventually the counter variable 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 while loop. 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.

Connect with me:
     
Newsletter - Get all my free tips!