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 Arrays
8 Java Strings
9 Java Operations
10 Java if statements
11 Java Switch Statements
12 Java for Loops
13 Java while Loops
14 Java Classes
15 Java Fields
16 Java Methods
17 Java Constructors
18 Java Packages
19 Java Access Modifiers
20 Java Inheritance
21 Java Nested Classes
22 Java Abstract Classes
23 Java Interfaces
24 Java Interfaces vs. Abstract Classes
25 Java Enums
26 Java Annotations
27 Java Main Program
28 Java Lambda Expressions
29 Java Exercises




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!