Java for Loop
In this page:
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
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
System.out.println(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
for (int i = 5; i > 0; i--) {
System.out.println(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 10; i += 2) {
System.out.println(i);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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]);
}
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: