← Back to Chapters

Java Nested Loops

? Java Nested Loops

? Quick Overview

Nested loops in Java mean placing one loop inside another loop. The inner loop runs completely for each iteration of the outer loop. Nested loops are commonly used for working with patterns, tables, matrices, and multi-dimensional data.

? Key Concepts

  • One loop inside another loop
  • Inner loop executes fully for each outer loop iteration
  • Used for patterns, grids, tables, and matrices
  • Works with for, while, and do-while

? Syntax / Theory

The most common nested loop structure is a for loop inside another for loop.

? View Code Example
// General syntax of nested for loop
for(int i=1;i<=rows;i++){
for(int j=1;j<=columns;j++){
System.out.print("* ");
}
System.out.println();
}

? Code Example

Printing a simple square star pattern using nested loops.

? View Code Example
// Java program to print a 5x5 star pattern
class NestedLoops{
public static void main(String[] args){
for(int i=1;i<=5;i++){
for(int j=1;j<=5;j++){
System.out.print("* ");
}
System.out.println();
}
}
}

? Live Output / Explanation

The outer loop controls the number of rows. The inner loop prints stars in each row. After the inner loop finishes, a new line is printed, creating a square pattern.

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

? Interactive: Pattern Generator

Change the number of rows to simulate the Java logic in real-time!

* * * * * * * * * * * * * * * * * * * * * * * * *

✅ Tips & Best Practices

  • Keep loop conditions simple and readable
  • Avoid unnecessary nesting to improve performance
  • Use meaningful variable names like row and col
  • Understand loop flow before writing complex logic

? Try It Yourself

  • Create a right-angle triangle pattern
  • Print a multiplication table using nested loops
  • Try nested while loops instead of for
  • Generate number patterns (1 22 333)