Loops (While Loops)

The while loop is used to repeat a block of code as long as a particular condition is true.

The syntax of the while loop in Java is

While (condition) {

block of code

}

The following application will result in the same printout as the For - Next program we looked at in the last section.

 

Copy the following code into a text editor and
save it as whileloop.java.

class whileloop {
public static void main (String args[]){
  int x = 0;
  while (x<20) {
  
  System.out.println("x = " + x + "  x squared = " + x*x);
  
   x++; }
      
  }
}
Line 1 Designates that we are defining
a new class called forloop.

Line 3 declares x as an integer variable
and initializes it to 0

Line 4 sets up the loop conditions.
It will continue to execute
as long as x is less than 20.

Line 5 sends the values for
x and x squared to the
system output device.

Line 6 increments x

 

After compiling and running this program the output should be

x = 0  x squared = 0
x = 1  x squared = 1
x = 2  x squared = 4
x = 3  x squared = 9
x = 4  x squared = 16
x = 5  x squared = 25
x = 6  x squared = 36
x = 7  x squared = 49
x = 8  x squared = 64
x = 9  x squared = 81
x = 10  x squared = 100
x = 11  x squared = 121
x = 12  x squared = 144
x = 13  x squared = 169
x = 14  x squared = 196
x = 15  x squared = 225
x = 16  x squared = 256
x = 17  x squared = 289
x = 18  x squared = 324
x = 19  x squared = 361

Notice that x = 20 is not printed. The value of x actually does get to 20 but the loop exits at that point therefore it is never printed. The controlling decision While (x < 20) could be changed to x <= 20 if we wanted the loop to continue to that point.

The Do While loop is very similar except that it executes a given statement until the condition is false.

A loop can be used to accept all command line arguments as you can see in this example.

Go to the next topic: Arrays

Back to the Table of Contents