Java For Loop

Learn Java for loop with syntax, examples, nested loops, enhanced for loop, and best practices.

What is For Loop?

for loop is used to repeat code multiple times.

Syntax

for(initialization; condition; update){

    code;

}

Example

for(int i = 1; i <= 5; i++){

    System.out.println(i);

}

Output

1
2
3
4
5

Infinite Loop

for(;;){

    System.out.println("Infinite");

}

Nested Loop

for(int i=1; i<=3; i++){

    for(int j=1; j<=2; j++){

        System.out.println(i + " " + j);

    }

}

Enhanced For Loop

int numbers[] = {1,2,3};

for(int n : numbers){

    System.out.println(n);

}