🔁 for loop in Java
One of the most powerful tools in Java is the for loop. Whether you want to repeat a task 10 times or process millions of records, the for loop is your go-to. 🚀
🧐 What is a for loop?
A for loop is used to execute a block of code repeatedly until a given condition is false.
👉 Syntax:
for(initialization; condition; update) {
// Code to be executed
}
🔍 Breaking it Down
-
Initialization → Runs once, sets the starting point.
-
Condition → Checked before each loop; if false, loop stops.
-
Update → Executes after each iteration, usually increments/decrements a counter.
📌 Example:
for(int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
💡 Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
🎯 Why use a for loop?
✔️ Best when you know exactly how many times you want to run the loop.
✔️ Cleaner and more concise compared to while loops.
✔️ Perfect for arrays, lists, and collections.
⚡ Types of for loops in Java
-
Standard for loop
-
Example above 👆
-
-
Enhanced for loop (for-each loop)
-
Best for arrays & collections.
int numbers[] = {10, 20, 30}; for(int n : numbers) { System.out.println(n); } -
-
Nested for loop
-
A loop inside another loop (commonly used in patterns & matrices).
for(int i = 1; i <= 3; i++) { for(int j = 1; j <= 3; j++) { System.out.print(i + "," + j + " "); } System.out.println(); } -
Examples:
Got it 👍
Here are some popular, practical, and engaging examples of for loop in Java that you can post on your website to keep readers hooked 👇
🌟 Popular Examples of for loop in Java
1️⃣ Print Numbers from 1 to 10
for(int i = 1; i <= 10; i++) {
System.out.print(i + " ");
}
Output:
1 2 3 4 5 6 7 8 9 10
2️⃣ Print the Multiplication Table
int num = 5;
for(int i = 1; i <= 10; i++) {
System.out.println(num + " x " + i + " = " + (num * i));
}
Output (for 5):
5 x 1 = 5
5 x 2 = 10
...
5 x 10 = 50
3️⃣ Calculate Sum of First N Numbers
int sum = 0;
for(int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("Sum = " + sum);
Output:
Sum = 5050
4️⃣ Reverse a String
String str = "Java";
for(int i = str.length() - 1; i >= 0; i--) {
System.out.print(str.charAt(i));
}
Output:
avaJ
5️⃣ Pattern Printing (Star Pyramid)
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
6️⃣ Iterate an Array (Using for-each loop)
int[] arr = {10, 20, 30, 40, 50};
for(int num : arr) {
System.out.print(num + " ");
}
Output:
10 20 30 40 50