← Back to Core Java Course | Chapter 4: Control Flow | Lesson 7 of 9

Java for Loop

Basic for Loop

A for loop packs initialization, the continue condition, and the update step into a single header line, making it the natural choice whenever you know in advance roughly how many times you need to iterate.

Example: Basic for Loop

java
public class Main {
	public static void main(String[] args) {
		for (int i = 0; i < 3; i++) {
			System.out.println(i);
		}
	}
}

Decrementing for Loops

Initializing the loop variable at a high value and using i-- as the update step walks the loop backward, which is handy for tasks like processing an array from its last element to its first.

Example: Decrementing for Loops

java
public class Main {
	public static void main(String[] args) {
		for (int i = 5; i > 0; i--) {
			System.out.println(i);
		}
	}
}

Iterating with Custom Steps

The update expression isn't limited to i++ -- writing i += 2 steps by twos, letting you visit every other index or count by any custom increment your logic needs.

Example: Iterating with Custom Steps

java
public class Main {
	public static void main(String[] args) {
		for (int i = 0; i < 10; i += 2) {
			System.out.println(i);
		}
	}
}

Iterating over Arrays

Because array indices run from 0 to length-1, a for loop like for (int i = 0; i < arr.length; i++) is the standard, idiomatic way to visit and process every element of an array in order.

Example: Iterating over Arrays

java
public class Main {
	public static void main(String[] args) {
		int[] arr = {10, 20, 30};
		for (int i = 0; i < arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
}

Nested for Loops

An inner for loop runs to completion for every single iteration of its enclosing outer loop -- with two loops each running n times, that's n squared total iterations, the classic pattern behind processing 2D grids or comparing all pairs in a list.

Example: Nested for Loops

java
public class Main {
	public static void main(String[] args) {
		for (int i = 0; i < 2; i++) {
			for (int j = 0; j < 2; j++) {
				System.out.println(i + "," + j);
			}
		}
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.