Jenkov.com
Tutorials Books About
Java Language

1 Java Tutorial
2 What is Java?
3 Java Core Concepts
4 Java Syntax
5 Java Variables
6 Java Data Types
7 Java Strings
8 Java Operations
9 Java if statements
10 Java Switch Statements
11 Java for Loops
12 Java while Loops
13 Java Classes
14 Java Fields
15 Java Methods
16 Java Constructors
17 Java Packages
18 Java Access Modifiers
19 Java Inheritance
20 Java Nested Classes
21 Java Abstract Classes
22 Java Interfaces
23 Java Interfaces vs. Abstract Classes
24 Java Enums
25 Java Annotations
26 Java Main Program
27 Java Lambda Expressions




Java while Loops


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!