When one loop appears inside another, you have nested loops in Java. Searchers often look for nested for loop Java, nested while loop Java, or a nested loop example in Java for patterns, tables, matrices, and menu-driven input. You can combine for, while, and do-while in any order; the inner loop completes (or exits) for each step of the outer loop.
Below, every text block is exact program output from OpenJDK 17.0.17 on Linux for the matching program. For single-loop basics first, see the Java for loop examples and while loop in Java guides on this site.
Nested for loop in Java
The inner for runs for every iteration of the outer for. If the outer runs n times and the inner runs m times per outer step, the inner body runs up to n × m times.
// Print a descending-width star pattern
class NestedForStar {
public static void main(String[] args) {
int i, j;
for (i = 1; i <= 5; i++) {
for (j = i; j <= 5; j++) {
System.out.print("*");
}
System.out.println();
}
}
}*****
****
***
**
*Nested while loop in Java
The same n × m idea applies: the inner while runs as long as its condition is true for each pass of the outer while.
// Multiplication tables for 5 and 6
class NestedWhileTables {
public static void main(String[] args) {
int i = 5, j;
while (i <= 6) {
System.out.println("Multiplication table of " + i);
j = 1;
while (j <= 10) {
System.out.println(i + " * " + j + " = " + (i * j));
j++;
}
i++;
}
}
}Multiplication table of 5
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
Multiplication table of 6
6 * 1 = 6
6 * 2 = 12
6 * 3 = 18
6 * 4 = 24
6 * 5 = 30
6 * 6 = 36
6 * 7 = 42
6 * 8 = 48
6 * 9 = 54
6 * 10 = 60Nested do-while loop in Java (Scanner menu)
A do-while always runs the body once before checking the condition, which fits menus. The inner do-while below reads n numbers for addition or multiplication.
Loop exit: an older pattern used while (ch <= 4), which keeps the menu running after choices 1 or 2 because ch stays 1 or 2. Here the outer loop uses while (ch == 1 || ch == 2) so entering 3 exits cleanly after the last menu prompt.
import java.util.Scanner;
class MenuNestedDo {
public static void main(String[] args) {
int ch, count;
Scanner sc = new Scanner(System.in);
int a, result, n;
do {
System.out.println("Enter your choice \n1. Addition \n2. Multiplication");
ch = sc.nextInt();
switch (ch) {
case 1:
count = 0;
result = 0;
System.out.println("Enter how many numbers you want to add");
n = sc.nextInt();
do {
System.out.println("Enter a number " + (count + 1));
a = sc.nextInt();
result = result + a;
count++;
} while (count < n);
System.out.println("Summation result is " + result);
break;
case 2:
count = 0;
result = 1;
System.out.println("Enter how many numbers you want to multiply");
n = sc.nextInt();
do {
System.out.println("Enter a number " + (count + 1));
a = sc.nextInt();
result = result * a;
count++;
} while (count < n);
System.out.println("Multiplication result is " + result);
break;
}
} while (ch == 1 || ch == 2);
}
}Sample stdin (one integer per line): 1, 3, 10, 20, 30, then 2, 3, 10, 20, 30, then 3 to quit.
Enter your choice
1. Addition
2. Multiplication
Enter how many numbers you want to add
Enter a number 1
Enter a number 2
Enter a number 3
Summation result is 60
Enter your choice
1. Addition
2. Multiplication
Enter how many numbers you want to multiply
Enter a number 1
Enter a number 2
Enter a number 3
Multiplication result is 6000
Enter your choice
1. Addition
2. MultiplicationIf Scanner misbehaves when you mix nextInt and nextLine in larger programs, read how to skip a line in Java Scanner—that pattern explains many nextInt “line:column” style issues in IDEs.
Labeled break (outer nested loop)
Oracle’s tutorial shows break label to exit an outer loop from inside an inner loop (for example, searching a 2D array). This is a common “nested loop Java” follow-up question.
public class LabeledBreakDemo {
public static void main(String[] args) {
outer:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
System.out.println("break outer at i=" + i + " j=" + j);
break outer;
}
System.out.println("i=" + i + " j=" + j);
}
}
System.out.println("done");
}
}i=1 j=1
i=1 j=2
i=1 j=3
i=2 j=1
break outer at i=2 j=2
doneHybrid nested loops (mixed styles)
Repeated words — while + for
Outer while walks each word; inner for scans the rest of the array. Mark duplicates with a sentinel string "0" and compare with .equals, not !=.
public class RepeatedWordsHybrid {
public static void main(String[] args) {
String s = "Life is like a book. Life is like a cup of tea. Life is like a rose garden. Life is like a dream";
int count;
s = s.toLowerCase();
String[] w = s.split(" ");
System.out.println("Finding repeated words in a string : ");
int i = 0;
while (i < w.length) {
count = 1;
for (int j = i + 1; j < w.length; j++) {
if (w[i].equals(w[j])) {
count++;
w[j] = "0";
}
}
if (count > 1 && !w[i].equals("0")) {
System.out.println(w[i]);
}
i++;
}
}
}Finding repeated words in a string :
life
is
like
aTranspose of a matrix — for + while + nested for
public class TransposeHybrid {
public static void main(String[] args) {
int r, c;
int[][] a = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
r = a.length;
c = a[0].length;
int[][] t = new int[c][r];
int j;
for (int i = 0; i < c; i++) {
j = 0;
while (j < r) {
t[i][j] = a[j][i];
j++;
}
}
for (int i = 0; i < c; i++) {
for (j = 0; j < r; j++) {
System.out.print(t[i][j] + " ");
}
System.out.println();
}
}
}1 4 7
2 5 8
3 6 9 Pattern — do-while + for
The outer do-while advances the row; the inner for prints one line. The condition i <= n produces five rows for n = 5 (including the row where the diagonal is all stars).
public class PatternDoWhileFor {
public static void main(String[] args) {
int i = 1, j, n = 5;
do {
for (j = n; j >= 1; j--) {
if (j != i) {
System.out.print(j);
} else {
System.out.print("*");
}
}
System.out.println();
i++;
} while (i <= n);
}
}5432*
543*1
54*21
5*321
*4321Summary
Nested loops in Java let you handle 2D data, generate patterns, and build input-driven flows. Use nested for or nested while when the iteration counts are clear; use nested do-while when the first pass must always run. Remember break/continue default to the innermost loop, and use a label when the outer loop must stop from inside. For Scanner-heavy menus, plan how nextInt and nextLine interact so nested reads stay predictable.
Frequently Asked Questions
1. How many times does a nested loop run in Java?
Up to the product of outer and inner iterations. If the outer loop runs n times and the inner runs m times per outer step, the inner body can run about n times m times, often written O(n times m) in complexity terms.2. What is the difference between a nested for loop and a nested while loop in Java?
Only the loop style; nesting means one loop is inside another. for loops bundle initialization, test, and update in the header; while and do-while use a boolean condition with updates you place in the body.3. How do you break out of nested loops in Java?
An unlabeled break only exits the innermost loop. For the outer loop, use a labeled break on the outer statement, or refactor the search into a method and return early.4. Does break or continue affect the outer loop in nested loops?
By default, no; they target the innermost loop or switch. Use a label on the outer loop with break label or continue label to affect an outer loop.5. Why does Java Scanner nextInt fail after nextLine in nested input loops?
nextInt reads a number but leaves the end-of-line in the buffer, so a following nextLine can read an empty line. Mixing nextInt and nextLine in menus often needs an extra nextLine to consume the rest of the line, or use nextLine and parse integers.6. Is deep nesting a good idea in Java?
Deeply nested loops hurt readability. Prefer extracting methods, using early returns, or streams when the logic stays clearer.References
The for Statement (Oracle Java Tutorials)
The while and do-while Statements (Oracle)
Branching Statements — labeled break (Oracle)
Class Scanner (Java SE 17)

