In this tutorial, we will learn how to use for loop in Java with the help of examples. how many times you want to loop through a block of code, use the for loop.


Syntax:

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}


Example:

package javaapplication;

/**
 *
 * @author Rathorji
 */
public class JavaApplication {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        int n = 5;
        // for loop  
        for (int i = 1; i <= n; ++i) {
            System.out.println(i);
        }

    }

}


output:

run:
1
2
3
4
5


For-Each Loop

loop through elements in an array


Example:

package javaapplication;

/**
 *
 * @author Rathorji
 */
public class JavaApplication {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        String[] persons = {"Rakesh", "Rathorji", "John", "Doe"};
        for (String i : persons) {
            System.out.println(i);
        }
    }

}



output:

run:
Rakesh
Rathorji
John
Doe