Nested loops are fine as long as they describe the correct algorithm.

Nested loops have performance considerations (see @Travis-Pesetto's answer), but sometimes it's exactly the correct algorithm, e.g. when you need to access every value in a matrix.

Labeling loops in Java allows to prematurely break out of several nested loops when other ways to do this would be cumbersome. E.g. some game might have a piece of code like this:

Player chosen_one = null;
...
outer: // this is a label
for (Player player : party.getPlayers()) {
  for (Cell cell : player.getVisibleMapCells()) {
    for (Item artefact : cell.getItemsOnTheFloor())
      if (artefact == HOLY_GRAIL) {
        chosen_one = player;
        break outer; // everyone stop looking, we found it
      }
  }
}

While code like the example above may sometimes be the optimal way to express a certain algorithm, it is usually better to break this code into smaller functions, and probably use return instead of break. So a break with a label is a faint code smell; pay extra attention when you see it.

Answer from 9000 on Stack Exchange
🌐
Programiz
programiz.com › java-programming › nested-loop
Nested Loop in Java (With Examples)
In the above example, the outer loop iterates 3 times and prints 3 weeks. And, the inner loop iterates 7 times and prints the 7 days. We can also create nested loops with while and do...while in a similar way.
🌐
Runestone Academy
runestone.academy › ns › books › published › csjava › Unit4-Iteration › topic-4-4-nested-loops.html
4.4. Nested For Loops — CS Java
When a loop is nested inside another loop, the inner loop is runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.
Top answer
1 of 6
64

Nested loops are fine as long as they describe the correct algorithm.

Nested loops have performance considerations (see @Travis-Pesetto's answer), but sometimes it's exactly the correct algorithm, e.g. when you need to access every value in a matrix.

Labeling loops in Java allows to prematurely break out of several nested loops when other ways to do this would be cumbersome. E.g. some game might have a piece of code like this:

Player chosen_one = null;
...
outer: // this is a label
for (Player player : party.getPlayers()) {
  for (Cell cell : player.getVisibleMapCells()) {
    for (Item artefact : cell.getItemsOnTheFloor())
      if (artefact == HOLY_GRAIL) {
        chosen_one = player;
        break outer; // everyone stop looking, we found it
      }
  }
}

While code like the example above may sometimes be the optimal way to express a certain algorithm, it is usually better to break this code into smaller functions, and probably use return instead of break. So a break with a label is a faint code smell; pay extra attention when you see it.

2 of 6
28

Nested loops are frequently (but not always) bad practice, because they're frequently (but not always) overkill for what you're trying to do. In many cases, there's a much faster and less wasteful way to accomplish the goal you're trying to achieve.

For example, if you have 100 items in list A, and 100 items in list B, and you know that for each item in list A there's one item in list B that matches it, (with the definition of "match" left deliberately obscure here), and you want to produce a list of pairs, the simple way to do it is like this:

for each item X in list A:
  for each item Y in list B:
    if X matches Y then
      add (X, Y) to results
      break

With 100 items in each list, this will take an average of 100 * 100 / 2 (5,000) matches operations. With more items, or if the 1:1 correlation is not assured, it becomes even more expensive.

On the other hand, there's a much faster way to perform an operation like this:

sort list A
sort list B (according to the same sort order)
I = 0
J = 0
repeat
  X = A[I]
  Y = B[J]
  if X matches Y then
    add (X, Y) to results
    increment I
    increment J
  else if X < Y then
    increment I
  else increment J
until either index reaches the end of its list

If you do it this way, instead of the number of matches operations being based on length(A) * length(B), it's now based on length(A) + length(B), which means your code will run much faster.

🌐
Softuni
java-book.softuni.org › chapter-06-nested-loops-exam-problems.html
6.2. Nested Loops – Exam Problems · Programming Basics with Java
To solve the problem, we first need to calculate the dashes on the left, the middle dashes, the dashes on the right, and the whole length of the figure. Once we have declared and initialized the variables, we can begin drawing the figure by starting with the upper part. From the examples, we can figure out the structure of the first row, and create a loop that iterates n number of times.
🌐
W3Schools
w3schools.com › java › java_for_loop_nested.asp
Java Nested Loops
if else else if Short Hand If...Else Nested If Logical Operators Real-Life Examples Code Challenge Java Switch ... For Loop Nested Loops For-Each Loop Real-Life Examples Code Challenge Java Break/Continue Java Arrays
🌐
Softuni
java-book.softuni.org › chapter-06-nested-loops.html
Chapter 6.1 Nested Loops - Programming Basics with Java
The problem is similar to those of drawing rectangles and squares. We will use nested loops again, but there is a trick here. The difference is that the number of columns we need to print as output depends on the row we are on, not the input integer n. From the sample input and output data, we notice that the number of dollars depends on which line we are at the time of printing, i.e.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-nested-loops-with-examples
Java Nested Loops with Examples - GeeksforGeeks
July 12, 2025 - Note: There is no rule that a loop must be nested inside its own type.
🌐
University of Washington
courses.cs.washington.edu › courses › cse142 › 17wi › lectures › 01-11 › slides › 04-nested-loops-constants.pdf pdf
1 Building Java Programs Chapter 2 Nested Loops, Figures and Constants
Building Java Programs · Chapter 2 · Nested Loops, Figures and Constants · reading: 2.3 - 2.5 · 2 · 3 · Nested loops · reading: 2.3 · 4 · 5 · Nested loops · ! nested loop: A loop placed inside another loop. for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 10; j++) { ...
Find elsewhere
🌐
AlgoCademy
algocademy.com › link
Nested Loops in Java | AlgoCademy
July 12, 2025 - Recursion: Sometimes, recursion can be an alternative to nested loops for certain problems.
🌐
CodeGym
codegym.cc › java blog › loops in java › java nested loops
Java Nested Loops
April 2, 2025 - For example, for inside while or for inside for-each. However, it’s not the best programming practice. Such constructs significantly impair the readability of the code. So professional programmers try not to mix one with the other.
🌐
Stack Overflow
stackoverflow.com › questions › 58740267 › nested-loops-statements-practice-problem-in-java
eclipse - Nested Loops Statements Practice Problem in Java - Stack Overflow
Instead of printing j + " ", print "*". And your first loop should be from 0 to rows, and the second should be from 0 to rows - i.
🌐
GitHub
github.com › SoftUni › Programming-Basics-Book-Java-EN › blob › master › chapter-06-nested-loops-exam-problems.md
Programming-Basics-Book-Java-EN/chapter-06-nested-loops-exam-problems.md at master · SoftUni/Programming-Basics-Book-Java-EN
February 12, 2026 - To solve the problem, we first need to calculate the dashes on the left, the middle dashes, the dashes on the right, and the whole length of the figure. Once we have declared and initialized the variables, we can begin drawing the figure by starting with the upper part. From the examples, we can figure out the structure of the first row, and create a loop that iterates n number of times.
Author   SoftUni
🌐
University of Texas
cs.utexas.edu › ~scottm › cs305j › handouts › slides › Topic6NestedForLoops_4Up.pdf pdf
Topic 6 Nested for Loops
Based on slides for Building Java Programs by Reges/Stepp, found at · http://faculty.washington.edu/stepp/book/ CS305j Introduction to Computing · Nested For Loops · 1 · p · y · g · pp · Nested for loops · A for loop can contain any kind of statement in its body, including another ...
🌐
Runestone Academy
runestone.academy › ns › books › published › csawesome › Unit4-Iteration › topic-4-4-nested-loops.html
4.4. Nested For Loops — CSAwesome v1
When a loop is nested inside another loop, the inner loop runs many times inside the outer loop. In each iteration of the outer loop, the inner loop will be re-started. The inner loop must finish all of its iterations before the outer loop can continue to its next iteration.
🌐
TutorialsPoint
tutorialspoint.com › java-nested-loops-with-examples
Java Nested Loops with Examples
while (conditional expression) { // code will be executed till the conditional expression is true while (conditional expression) { // code will be executed till the conditional expression is true increment/decrement expression; // to increment/decrement loop variable } increment/decrement expression; // to increment/decrement loop variable } The following program will perform the addition of two matrices using a nested while loop.
🌐
Medium
medium.com › buzz-code › java-8-nested-loop-practice-multiplication-table-b7e6593a5a41
Java 8 | Nested Loop Practice — Multiplication Table | by Student Kim | Buzz Code | Medium
December 21, 2020 - As you see on my code, you see I put the initial for statement into another loop. This is called the Nested loop. When the variable j in the first loop initialized as 2, then the i in the second loop increased from 1 to 9. And then when j becomes 3, i goes from 1 to 9 again.
🌐
CodeChef
codechef.com › blogs › loops-in-java
Loops in Java - For, While, Nested Loops
August 7, 2024 - Learn how to use Java loops effectively. This guide covers for loops, while loops, nested loops, and practical coding examples for beginners.
🌐
Softuni
java-book.softuni.org › chapter-07-complex-loops-exam-problems.html
7.2. More Complex Loops – Exam Problems · Programming Basics with Java
October 5, 2018 - The other tricky part in this problem is that, apart from the check above, we need an additional one - if the number is equal to the "stop" number entered from the console on the third line. To reach this check, the number we're checking has to pass the check above. That's why we add one more if statement nested in the previous one. If the condition is true, we have to stop printing. We can achieve this with the break operator which will lead us out of the for loop.