for loop

For loop Java Example (with video)

In this post, we feature a comprehensive For loop Java example. If you need to execute a block of code many times, you will have to use the for loop or the enhanced for loop java provides.
Java provides three looping mechanisms, which are the following:

If you need to execute a block of code many times, then you will definitely have to use this mechanism.
Java provides three ways to iterate:

  • while Loop
  • do-while Loop
  • for Loop

In this example, we will show how to use the for loop mechanism. Also, we will show the enhanced for loop, which was introduced in Java 5 and it is mainly used for Arrays.

You can also check Loops in Java in the following video:

For loop, while loop and do while loop in Java – Video
For loop Java

1. Syntax of For loop

The for statement provides a compact way to iterate over a range of values until a particular condition is satisfied. The general form of the for statement is the one following:

for (initializations; condition; update expressions) {
          //statement expressions
}
  • initializations: This expression declares and initializes the loop control variable. Note that you can have as many declarations and initialization as you like. They are executed only once when the loop begins.
  • condition: If the condition evaluates to true, the statement expressions are executed. If the condition evaluates to false, the loop terminates without the execution of the body of the loop.
  • update expressions: The update expression is invoked after each execution of the body of the loop and updates the loop control variable. You can have multiple update expressions.

2. For loop Java Example

Let’s see an example of the for loop mechanism. Create a java class named ForLoopExample.java with the following code:

ForLoopExample.java

package com.javacodegeeks.javabasics.forloop;

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

        for (int i = 0; i < 5; i++) {
            System.out.println("i is: " + i);
        }

        System.out.println("Print again the i values, with different condition");

        for (int i = 0; i <= 5; i++) {
            System.out.println("i is: " + i);
        }

        System.out.println("Print the array Cities");
        String[] cities = { "Athens", "Thessaloniki", "Chania", "Patra",
                "Larissa" };

        for (int i = 0; i < cities.length; i++) {
            System.out.println(cities[i]);
        }

         System.out.println("Example with multiple  declarations,initialiazations and update expressions");

        for(int i=0,j=1,k=2;i<=10&&j<=11&&k<=12;i++,j=j+2,k=j+3){
             System.out.println("i is: " + i); 
             System.out.println("j is: " + j);
             System.out.println("k is: " + k);     
        }
    }
}

In the above code, we can see two loops that seem to be the same but they have a basic difference in their conditions. The first loop evaluates to true as long as the i value is strictly less than 5 but the second loop evaluates to true even when the i value is equal to 5. Afterward, we have another loop printing an array named “cities”. The condition evaluates to false when the counter i is greater than or equal to the array’s length. The last loop shows how to write a loop with multiple declarations, initializations, and update expressions. We initialize i, j and k (The type must be the same), then we have the condition and then we add some numbers to the variables.
If we run the above code, we will get the following results:

Output

i is: 0
i is: 1
i is: 2
i is: 3
i is: 4
Print again the i values, with different condition
i is: 0
i is: 1
i is: 2
i is: 3
i is: 4
i is: 5
Print the array Cities
Athens
Thessaloniki
Chania
Patra
Larissa
Example with multiple  declarations,initialiazations and update expressions
i is: 0
j is: 1
k is: 2
i is: 1
j is: 3
k is: 6
i is: 2
j is: 5
k is: 8
i is: 3
j is: 7
k is: 10
i is: 4
j is: 9
k is: 12

As we see in the output, the first loop does not print the i value when the i is equal to 5, while the second loop does. It may seem that this is too much detail, but actually, one more or less execution of the loop may be critical for each program.

3. Syntax of the “enhanced” For loop

As we mentioned in the introduction, Java 5 introduced the enhanced for loop as a simpler way to iterate through all the elements of a Collection. This for loop is commonly used by arrays, when you wish to step through the elements of the array in first-to-last order, and you do not need to know the index of the current element. The syntax of the enhanced for loop java provides is the following:

for (declaration : expression) {
   //Statement expressions
}
  • declaration: A new variable is declared, which is of the same type as the type of the elements of the array. This variable is used in the body of the loop and its value is the same as the current array element. The colon in the syntax can be read as “in.”
  • expression: This evaluates to the array you need to loop through. The expression can be an array variable or method call that returns an array.

4. Example of the “enhanced” For loop

Let’s see an example of the enhanced for loop mechanism. Create a java class named EnhancedForLoopExample.java with the following code:

EnhancedForLoopExample.java

package com.javacodegeeks.javabasics.forloop;

public class EnhancedForLoopExample {

    public static void main(String args[]) {
        String[] cities = { "Athens", "Thessaloniki", "Chania", "Patra",
                "Larissa" };
        //Same can be done with  a List such as:
       //List<String> cities = new ArrayList<>();
       //cities.add("Athens");
       //cities.add( "Thessaloniki" ); 
       //cities.add( "Chania" ); 
       //cities.add ("Patra" ); 
       //cities.add ("Larissa" );  
        for (String cityname : cities) {
            System.out.println(cityname);
        }

    }
}

In the above code, we use the array from the previous example and print it with the enhanced for loop java provides. The declaration expression is a variable cityname which is of type String, just as the type of the elements of the array cities.

Output

Athens
Thessaloniki
Chania
Patra
Larissa

6. Download the Source Code

This was a For loop Java example.

Download
You can download the source code from here: Java For loop Example

Last updated on March 2nd, 2022

Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button