⬅ Previous Topic
Java LoopsNext Topic ⮕
Java For-Each Loop⬅ Previous Topic
Java LoopsNext Topic ⮕
Java For-Each LoopThe for loop in Java is used to repeat a block of code a certain number of times. It's concise, predictable, and incredibly useful when you know in advance how many times a loop should run.
for (initialization; condition; update) {
// code block to be executed
}
This syntax has three parts:
true
.public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
}
}
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation: The loop starts with i = 1
. As long as i <= 5
, the loop executes and prints the current value. After every iteration, i++
increases i
by 1.
for (int i = 5; i > 0; i--) {
System.out.println(i);
}
5
4
3
2
1
Here, we reverse the iteration by starting at 5 and decreasing i
until it becomes less than or equal to 0.
for (int i = 0; i <= 10; i += 2) {
System.out.println("Even: " + i);
}
Even: 0
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10
Instead of incrementing by 1, here we increment by 2 to skip even numbers directly.
One of the most common use cases for a for
loop is iterating over arrays:
String[] fruits = { "Apple", "Banana", "Mango" };
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
Apple
Banana
Mango
A for loop without a condition can result in an infinite loop:
for (;;) {
System.out.println("This goes on forever...");
}
This loop runs endlessly since there's no condition to stop it. Use such loops carefully, often in conjunction with a break
statement.
for (int i = 1; i <= 10; i++) {
if (i == 6) break;
System.out.println(i);
}
1
2
3
4
5
Once i == 6
, the loop exits. The break
statement is often used to terminate loops early based on a condition.
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
1
2
4
5
When i == 3
, the continue
statement skips that iteration and continues with the next one.
Imagine checking your emails every morning for the next 7 days. A for
loop is like automating this task: "Start on Monday, repeat daily, and stop after Sunday." Simple, predictable, effective — just like a for loop!
for
loop is executed only once?for
loop is checked after each iteration.for (int i = 5; i > 0; i--) {
System.out.println(i);
}
for
loop by using its index values.continue
statement inside a for loop?⬅ Previous Topic
Java LoopsNext Topic ⮕
Java For-Each LoopYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.