Java For Loop
A for loop is the go-to choice when you already know how many times you want to repeat something. It packs the starting value, the condition, and the update step into a single tidy line, which makes counting loops short and easy to read.
The anatomy of a for loop
A for loop has three parts separated by semicolons inside the parentheses. First the initialization runs once, then before every pass the condition is checked, and after every pass the update runs. Keeping all three in one place makes it easy to see at a glance how the loop behaves.
Counting up with a for loop
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
// Output:
// Count: 1
// Count: 2
// Count: 3
// Count: 4
// Count: 5- Initialization (int i = 1): runs a single time before anything else.
- Condition (i <= 5): checked before each pass; the loop continues while it is true.
- Update (i++): runs at the end of each pass to move things forward.
Counting in different ways
You are not limited to counting up by one. You can count down, or step by larger amounts by changing the update part. This example counts backward and prints only even numbers by stepping down two at a time.
Counting down by twos
for (int i = 10; i > 0; i -= 2) {
System.out.println(i);
}
// Output:
// 10
// 8
// 6
// 4
// 2A real-world use
Because a for loop gives you an index number on each pass, it is a natural fit for walking through an array position by position when you need to know where you are.
Looping over an array by index
String[] fruits = {"apple", "banana", "cherry"};
for (int i = 0; i < fruits.length; i++) {
System.out.println((i + 1) + ". " + fruits[i]);
}
// Output:
// 1. apple
// 2. banana
// 3. cherryExercise: Java For Loop
What are the three parts separated by semicolons inside a standard for loop's parentheses?