Java For Loop
The Java for loop is a fundamental control structure used to repeat a
block of code a specific number of times. It is the preferred loop when
the number of iterations is known in advance, making programs more concise
and readable compared to while loops.
What Is a for Loop in Java?
A for loop combines initialization, condition checking, and iteration
update in a single line, making it ideal for counter-controlled
repetition.
Syntax
for (initialization; condition; update) {
// code to execute each iteration
}
How It Works
- Initialization runs once before the loop starts
- Condition is evaluated before each iteration
- Update executes after each loop cycle
Example 1: Display Squares of Numbers
This program prints numbers from 1 to 5 along with their
squares.
public class NumberSquares {
public static void main(String[] args) {
for (int num = 1; num <= 5; num++)
{
int square = num *
num;
System.out.println("Number: "
+ num + ", Square: " + square);
}
}
}
Example 2: Print Multiplication Table
This example generates the multiplication table of 7.
public class MultiplicationTable {
public static void main(String[] args) {
int base = 7;
for (int i = 1; i <= 10; i++)
{
System.out.println(base + " x
" + i + " = " + (base * i));
}
}
}
Example 3: Calculate Factorial
This program calculates the factorial of a given number using a for
loop.
public class FactorialForLoop {
public static void main(String[] args) {
int n = 5;
long factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
System.out.println("Factorial of " + n + "
is " + factorial);
}
}
Example 4: Reverse Countdown
A descending for loop can be used for countdown logic.
public class ReverseCountdown {
public static void main(String[] args) {
for (int seconds = 10; seconds >= 1;
seconds--) {
System.out.println("T-minus "
+ seconds);
}
System.out.println("Launch!");
}
}
for Loop That Never Executes
If the loop condition is false initially, the loop body is skipped
entirely.
public class ForLoopSkipDemo {
public static void main(String[] args) {
for (int start = 20; start < 10;
start++) {
System.out.println("This line will not
execute");
}
System.out.println("Loop skipped because
condition was false.");
}
}
When to Use a for Loop
Use a for loop when:
- The number of iterations is known
- You need a counter variable
- Iterating over ranges or sequences
- Processing arrays or collections by index
What Are Nested Loops in Java
A nested loop is a loop placed inside another loop. The outer loop
controls how many times the inner loop runs. For every single
iteration of the outer loop, the inner loop executes completely from
start to finish.
Nested loops are commonly used in Java for tasks that involve
multi-dimensional data, patter generation, matrix operations, and
tables.
How Nested Loops Work
- The outer loop executes first.
- For each outer loop iteration, the inner loop runs entirely.
- After the inner loop finishes, control returns to the outer loop for the next iteration.
Execution formula:
Total inner loop executions = outer loop count × inner loop
count
Example 1: Understanding Nested Loop Execution
This example demonstrates how the inner loop runs repeatedly for each
outer loop iteration.
public class NestedLoopDemo {
public static void main(String[] args) {
for (int row = 1; row <= 2; row++)
{
System.out.println("Outer
loop iteration: " + row);
for (int col = 1; col <=
3; col++) {
System.out.println(" Inner loop iteration: " + col);
}
}
}
}
Output
Outer loop iteration: 1
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Outer loop iteration: 2
Inner loop iteration: 1
Inner loop iteration: 2
Inner loop iteration: 3
Explanation
- Outer loop runs 2 times
- Inner loop runs 3 times per outer iteration
- Total inner executions = 2 × 3 = 6
Example 2: Multiplication Table Using Nested Loops
Nested loops are ideal for generating tables. The following
program prints a multiplication table from 1 to 5.
public class MultiplicationTable {
public static void main(String[] args)
{
int size = 5;
for (int i = 1; i <= size; i++)
{
for (int j = 1; j <=
size; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
}
}
Output
1 2 3 4
5
2 4 6 8
10
3 6 9 12
15
4 8 12 16
20
5 10 15 20 25
Why this works
- Outer loop controls rows
- Inner loop controls columns
- Each cell = row × column
Common Use Cases of Nested Loops in Java
- Printing patterns (triangles, pyramids, grids)
- Matrix operations
- Searching in 2D arrays
- Generating tables
- Comparing elements in lists
What Is the Java For-Each Loop?
The for-each loop (also called the enhanced for loop) is a
simplified looping construct in Java used to iterate over elements
of an array or collection (such as ArrayList, HashSet,
etc.).
It eliminates the need for index variables and boundary
conditions, making code cleaner, safer, and more
readable.
For-Each Loop Syntax
for (dataType element : collection) {
// code to execute for each element
}
Explanation
- data Type → type of elements in the array/collection
- element → variable holding the current item
- collection → array or collection being traversed
Why Use the For-Each Loop?
Compared to a traditional for loop, the for-each loop:
- Avoids index errors (Index Out Of Bounds Exception)
- Improves readability
- Reduces boilerplate code
- Automatically stops at the end of the collection
Example 1: Iterating Through a String Array
This program stores programming languages in an array and
prints each one using a for-each loop.
public class For Each String Example {
public static void main(String[] args)
{
String[] languages = {"Java",
"Python", "C++", "JavaScript"};
for (String lang : languages)
{
System.out.println("Language: " + lang);
}
}
}
Output
Language: Java
Language: Python
Language: C++
Language: JavaScript
Example 2: Processing Numeric Array Values
The following program calculates the sum and average of values
in an integer array using a for-each loop.
public class For Each Numbers Example {
public static void main(String[] args)
{
int[] scores = {85, 90, 78, 92,
88};
int total = 0;
for (int score : scores)
{
total +=
score;
}
double average = (double) total /
scores.length;
System.out.println("Total: " +
total);
System.out.println("Average: " +
average);
}
}
Output
Total: 433
Average: 86.6
When to Use the For-Each Loop
Use the enhanced for loop when:
- You only need to read elements
- Order matters but index does not
- Traversing arrays or collections
- Performing aggregation (sum, count, search)
Avoid it when:
- You need element index
- You modify array positions
- Iterating in reverse
- Removing elements during iteration