Loops in Java


Program loops are a form of flow control that allow sections of code to be executed repeatedly. Java supports four loop styles, these are:
  • the for loop
  • the foreach loop (This is also called the forin loop.)
  • the while loop
  • the do while loop

The Java for loop

The general syntax of the for statement is:
for ( initialization ; test ; increment ) statement
The initialization expression sets the loop variable to its first value (a loop variable can be declared here if required). The test expression is evaluated at the beginning of the loop after initialization expression. If the test expression is true the loop body statement is executed, at this point the increment expression is computed. If the test expression remains true the loop body statement is re-executed. This process of test, loop execution, incrementation continues until the test expression becomes false. The loop body statement can be either a simple statement or a compound statement, that is, a group of statements separated by the ; character and enclosed in curly brackets {}.

The Java foreach loop

The general syntax of the foreach statement is:
for (type loop-variable-identifier : expression ) statement
Here "type" is the data type of the loop-variable-identifier, so that
type loop-variable-identifier
forms a declaration. The expression after the : character must evaluate to an object or array the elements of with are commensurate with loop-variable-identifier. At each iteration of the loop the successive elements of the expression are assigned to the loop-variable-identifier and this variable is available for use in the loop body statement. The loop iterates through all of the elements of the expression. As before, the loop body statement can be a simple statement or a compound statement.

The Java while loop

The general syntax of the while statement is:
while (test) statement
The test expression is evaluated at the beginning of the loop. If the test expression is true the loop body statement is executed. If the test expression remains true the loop is re-executed. This process continues until the test expression becomes false. The loop body statement can be either a simple statement or a compound statement. When using a while loop any loop variables must be declare and initialized before the while statement. In addition, any loop variable incrementation must be performed in the loop body statement.

The Java do loop

The general syntax of the do while statement is:
do statement  while (test); 
The do loop first executes the loop body statement then evaluates the test expression. If the test expression is true the loop body statement is re-executed. This loop repartition ends when the test expression evaluates to false. In contrast to the other three types of loop the do loop always executes the loop body statement at least once. As is similar to the while loop, any loop variables must be declare and initialized before do statement and any loop variable incrementation must be performed in the loop body statement.

Example program

The next program demonstrates each of these loops. In every case the elements of a string array are displayed using the System.out.println method.
/**
Example of Java flow control.
We demonstrate four loop types in Java the Java if statement ,integer variables, String[] args,  array access and the println method.
*/


class  JavaLoops
{
 
public static  void main(String[] args)
  {
   
int i; //This integer is used in the for while and do loops.
   
System.out.println("Example of the for loop");
   
for(i=0;i<args.length;i++)
    {
     
System.out.println("Argument number " + i);
      System.out.println
("is " + args[i]);
   
}

   
System.out.println("Example of the foreach loop");
   
for(String strLoop: args)
    {
     
System.out.println("Argument is "+strLoop);
   
}

   
System.out.println("Example of the while loop");
    i=
0;   
   
while(i<args.length)
    {
     
     
System.out.println("Argument number " + i);
      System.out.println
("is " + args[i]);
      i++;
   
}

   
System.out.println("Example of the do loop");
   
if (args.length>0)
    { 
     
i=0;   
     
do
     
{
       
       
System.out.println("Argument number " + i);
        System.out.println
("is " + args[i]);
        i++; 
     
}while(i<args.length);
   
}
  } 
}

To use this source code cut and paste it into your text editor and save the file as "JavaLoops.java". To compile the program use the javac compiler. This translates the source code into byte code suitable for execution by the java run time environment. To run the program use the java command with the argument JavaLoops and with one or more program arguments of your own choice. So, to compile and run from the command line:
$ javac JavaLoops.java
$ java JavaLoops Felix Krull
Example of the for loop
Argument number 0
is Felix
Argument number 1
is Krull
Example of the foreach loop
Argument is Felix
Argument is Krull
Example of the while loop
Argument number 0
is Felix
Argument number 1
is Krull
Example of the do loop
Argument number 0
is Felix
Argument number 1
is Krull
$ 
Note
  • In the for, while and do loops the loop incrementation variable i is used. In the case of the foreach loop we don't need a loop incrementation variable. The successive values of the args array are automatically assigned to the strLoop variable.
  • The do loop always executes once if the do statement is executed. In this example we use an if statement to prevent the do loop from being encountered in case where the args array has 0 length. (Attempting to access an element array at a index beyond the length of the array will cause a run time error.)
  • To show the loop incrementation variable i we make use of the automatic conversion from primitive types to string types.

Summary

  • Loop are a form of flow control. They allow sections of code to be executed repeatedly.
  • Java support four kinds of loop. These are: the for loop, the foreach loop, the while loop and the do while loop.
  • The for loop allows loop variable declaration testing and incrementation in one statetment.
  • The foreach loop acts on reference types such as arrays. It automatically iterates over these types. It does not require a loop counter variable to do this.
  • The do loop will always execute the loop body statements at least once.


    • Previous The Java if statement

Custom Search

Tutorial
Your First Java Program
Primitive data types in Java
Basic arithmetic operations in Java
Using Strings in Java
More Strings in Java
The Java if statement
Loops in Java
The entire content of this site is subject to copyright.