Java Tutorial

Java Nested Loops

A loop inside a loop walks grids, tables, and pairs. The outer loop picks a row; the inner loop walks that row.

Outer and inner

Put one loop inside another when each pass of the outer work needs its own full pass of the inner work — rows and columns, each student and each quiz, every pair of items.

Example

public class Main {
  public static void main(String[] args) {
    for (int r = 1; r <= 3; r++) {
      for (int c = 1; c <= 3; c++) {
        System.out.print("(" + r + "," + c + ") ");
      }
      System.out.println();
    }
  }
}

Print a rectangle of stars

The classic drill: outer loop = rows, inner loop = columns. Reset or print a newline after each row finishes.

Example

public class Main {
  public static void main(String[] args) {
    int rows = 3;
    int cols = 5;
    for (int r = 0; r < rows; r++) {
      for (int c = 0; c < cols; c++) {
        System.out.print("*");
      }
      System.out.println();
    }
  }
}

Multiplication table

Nested counted loops are a natural fit for a small times table. Keep the print format tidy so columns line up.

Example

public class Main {
  public static void main(String[] args) {
    for (int a = 1; a <= 4; a++) {
      for (int b = 1; b <= 4; b++) {
        System.out.print(a * b + "\t");
      }
      System.out.println();
    }
  }
}

Name the indices for what they mean (row, col, i, j). Nested i / j is fine once the pattern is clear.

Cost: product of the bounds

If the outer loop runs R times and the inner runs C times each, the body runs aboutR × C times. That is fine for small grids; watch it when both bounds grow large.

Example — count pairs

public class Main {
  public static void main(String[] args) {
    int count = 0;
    for (int i = 0; i < 10; i++) {
      for (int j = 0; j < 10; j++) {
        count++;
      }
    }
    System.out.println(count);   // 100
  }
}

Accidental nesting (a search loop inside another search with no early exit) is a common performance bug. Ask whether every combination is truly needed.

Try It Yourself

Exercise: Print a right triangle of * with 4 rows: one star on the first row, then two, then three, then four.

Show solution
for (int r = 1; r <= 4; r++) {
  for (int c = 1; c <= r; c++) {
    System.out.print("*");
  }
  System.out.println();
}

The inner loop’s upper bound is r, so each row is one star longer than the last.

Key Takeaways

  • Nested loops walk every combination of outer and inner indices — rows × columns.
  • Print a newline (or reset) after each outer pass when drawing grids.
  • Body runs about outerBound × innerBound times — mind the product.
  • Name indices clearly; use break / labels only when you must leave early.

Worked examples

The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.

Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.

Maths

Multiplication grid

An outer loop picks the row; an inner loop fills the columns. Nested for is the natural shape of a times table.

Example

public class Main {
  public static void main(String[] args) {
    for (int r = 1; r <= 3; r++) {
      for (int c = 1; c <= 3; c++) System.out.print(r * c + " ");
      System.out.println();
    }
  }
}

Physics

Sample a grid of points

Two nested ranges walk every (x, y) on a plate. Each pair can later become a voltage reading.

Example

public class Main {
  public static void main(String[] args) {
    for (int x = 0; x < 2; x++)
      for (int y = 0; y < 2; y++)
        System.out.println(x + "," + y);
  }
}

FAQ: Java Nested Loops

Common questions about this page.

What is the StudyGrid Java tutorial?

The StudyGrid Java tutorial is a full beginner-to-advanced track: syntax, types, input, loops, methods, classes, collections, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run java nested loops examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn java nested loops in this Java Java lesson (Java Nested Loops).

Is the Java editor the same as Try Python or Try C++?

No. Try Java compiles with javac at /java/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. Java lessons never open those editors.

Do I need to install a JDK to learn Java?

No. Open a chapter, click Try it in Java, and compile in the browser. You can also download a .java file and compile locally with javac.

Where should I start the Java tutorial?

Start at Java Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open Java Examples, then generics, map, and lambdas. Use Next at the bottom of each chapter.

Is the Java tutorial free?

Yes. The Java workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.