Java for loop

A visual representation of how Java for loop works. Know how to write simple and enhanced for loops with example code.

The for loop in Java

The Java for loop is used to iterate through the block of code over the range of values. For example,

int x;

for (x=0; x<10; x++){

System.out.println(x);

}

Java provides simple as well as “enhanced” for statement that is used with arrays and other collections.

I will show you how to use both ways in this tutorial.

Structure of for loop

for (initialization_expression; termination_expression; update) {

//Code to be executed here

}

The definition of each expression is given below:

Expression  Definition 
initialization When the for loop begins, the initialization expression initiates the loop. Also, this part of the loop executes only once.
termination The second expression is the termination expression. As long as the termination expression evaluates as true, the loop keeps on executing. When it becomes false, the loop ends.
increment/decrement (update) The third one is an increment or decrement operator. This expression is invoked after each iteration and so the value is increased or decreased.

The following section explains how you may use the ‘for’ loop in Java with code.

A demo of using for loop to display numbers

In this example, the for loop is used for displaying the numbers from 0 to 9. For that, the variable is assigned the value 0 as an initial expression.

The condition is to iterate the loop until the value of variable x is less than 10. In each iteration, the value of x is incremented by 1.

The code:

public class test1 {
    public static void main(String []args) {

    int x;
    for (x=0; x<10; x++){
           System.out.println("The value of x in this iteration= " + x);
    }    
    }
}

Output:

The value of x in this iteration= 0
The value of x in this iteration= 1
The value of x in this iteration= 2
The value of x in this iteration= 3
The value of x in this iteration= 4
The value of x in this iteration= 5
The value of x in this iteration= 6
The value of x in this iteration= 7
The value of x in this iteration= 8
The value of x in this iteration= 9

A demo of for loop with decrement operator

In this demo, the value of variable x is decremented by 10 in each iteration. The initial value is set as 100. The third expression is used as follows:

x=x-10

The Java code:

public class test1 {
    public static void main(String []args) {
    int x;
    for (x=100; x>1; x=x-10){
           System.out.println("x = " + x);
    }    

   }
}

Result:

x = 100
x = 90
x = 80
x = 70
x = 60
x = 50
x = 40
x = 30
x = 20
x = 10

You see, this is how the for loop is built:

    for (x=100; x>1; x=x-10){

Inside the curly braces, the system.out.println statement is used to display the value of x variable.

A demo of using the break statement in for loop

In this example of explaining the for loop of Java with the break statement, I initiated the variable x = 0.

In each iteration, the value of x is incremented by 10. The iteration should go on until the value of x is greater than 100.

However, inside the curly braces, after using the system.out.println for displaying the value of x, the if statement is used to check the value of the x variable.

If the value is equal to 50, the loop should break; have a look:

The Java code using for loop with break statement:

public class test1 {
    public static void main(String []args) {
    int x;

    for (x=0; x<100; x=x+10){

           System.out.println("x = " + x);
           if (x == 50) {
                   System.out.println("The Loop is broken");
                        break;
                    }
    }    
   }
}

Output:

x = 0
x = 10
x = 20
x = 30
x = 40
x = 50
The Loop is broken
The break statement in Java is a control flow statement used to terminate the execution of a loop prematurely.

A demo of using nested for loop

You can use a for loop inside another for loop when writing the Java programs. This is called nested for loop.

The nested for loop may be required if you need to run another loop for each item of the outer array.

In the following example:

  • An outer loop is used where the x variable is initiated from 0 and will loop until the value reaches 50. In each iteration, the value is incremented by 10.
  • In the inner loop, the variable z is initiated from 1 and increments by 1 in each iteration till the variable z value is less than 3.
  • Inside the curly braces of the inner loop, the value of x and z is summed and assigned to the variable y.
  • Finally, the System.out.println is used to display the current value of x, z, and y.

The nested for loop code:

public class test1 {
    public static void main(String []args) {
    int x,y,z;

    for (x=0; x<50; x=x+10){
      for (z=1; z<3; z++){   
                  y = x + z;
                System.out.println(x + "+" + z + " = " + y);
      }

    }    
   }
}

Output:

0+1 = 1
0+2 = 2
10+1 = 11
10+2 = 12
20+1 = 21
20+2 = 22
30+1 = 31
30+2 = 32
40+1 = 41
40+2 = 42

An example of enhanced for loop with an array

As mentioned earlier, you may use the for loop to iterate through the arrays or other collections in Java.

In this example, a numeric Java array is created with five elements.

After that, the “enhanced” for loop is used to iterate through that array, and System.out.println is used to display the array items:

The Java code with an array:

public class test1 {

    public static void main(String []args) {

 

        int[] arrNums = {10,20,30,40,50};

        for (int currElement : arrNums) {

            System.out.println("The array item: " + currElement);

        }  

 

    }

}

Output:

The array item: 10
The array item: 20
The array item: 30
The array item: 40
The array item: 50

You see, the currElement variable is used in the for loop which is followed by the array name.

In each iteration, the next element of the array is assigned to that variable which is displayed by using the System.out.println.

A demo of ‘for’ loop with a string array

Similarly, you may use the string array with for loop to iterate through its elements. See this example, where an array with three elements is created.

By using the for loop, the array items are displayed:

The Java code:

public class test1 {

    public static void main(String []args) {

 

        String[] arrstr = new String[3];

        arrstr[0] = "Houston";

        arrstr[1] = "Chicago";

        arrstr[2] = "Dallas";

        for (String currElement : arrstr) {

            System.out.println("The US city: " + currElement);

        }  

 

    }

}

Result:

The US city: Houston
The US city: Chicago
The US city: Dallas

You can see, how enhanced for loop makes it easier to iterate through array elements.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!