Java Star Patterns: 18 Loop Examples to Master Logic

Master nested loops and coordinate logic in Java with 18 star, hollow, symmetric, number, and alphabet pattern examples and runnable code.

N

NeuraQuiz Admin

May 14, 2026 • 17 min read • Updated November 18, 2026

Java Star Patterns: 18 Loop Examples to Master Logic

Java star patterns are one of the fastest ways to build real logical thinking while learning Java. Printing grids, triangles, pyramids, and diamonds on the console looks simple, yet every pattern trains core programming fundamentals: for loops, nested iteration, branching conditions, and coordinate mapping.

Java Nested Loops Logic Building and 2D Matrix Grid Tracing

Interviewers, university lab assignments, and coding warmups frequently test pattern problems because they reveal whether you truly understand how nested loops track rows, columns, and state.

Why Every Java Beginner Should Learn Star Patterns

Many beginners focus exclusively on memorizing syntax, yet syntax alone never builds problem-solving fluency. Pattern exercises force you to trace execution step by step.

Practicing star patterns helps you:

  • Strengthen analytical and spatial reasoning
  • Master nested loop boundaries and termination conditions
  • Build intuition for 2D row-and-column iteration
  • Gain confidence reading and debugging Java control flow
  • Prepare for entry-level technical screenings and lab exams

Each new shape challenges you to translate visual symmetry into exact loop indices.

Prerequisites for Learning Java Star Patterns

Before starting, you should understand:

ConceptImportance
VariablesStore values
Data TypesDefine information
for LoopsRepeat operations
if StatementsControl execution
System.out.print()Display output

With those five building blocks in place, every pattern below breaks down into predictable steps.

Understanding Loops in Java

Loops repeat a block of instructions until a condition turns false, letting you generate grids of any size without duplicating code.

The for Loop

A standard for loop combines initialization, a continuation check, and an increment in one header:

java
for(int i = 1; i <= 5; i++){
    System.out.println(i);
}

This loop prints the integers 1 through 5 on separate lines.

Nested Loops Explained

Star patterns rely on nested loops—one loop placed inside another:

java
for(int row = 1; row <= 3; row++){
    for(int col = 1; col <= 3; col++){
        System.out.print("*");
    }
    System.out.println();
}

Output:

text
***
***
***

The outer loop controls rows, while the inner loop prints columns across each row before System.out.println() advances to the next line. The diagram below shows how row (i) and column (j) coordinates map to spaces, stars, and hollow boundaries:

Java Star Patterns Nested Loop Coordinate Logic Infographic

The 3-Step Row-Column Matrix Trace Method

Rather than memorizing loop snippets for dozens of shapes, apply this repeatable three-step decomposition to any pattern problem you encounter in an exam or technical interview:

  1. Determine the Outer Loop Range (Total Rows n): Count how many horizontal lines appear from top to bottom. Your outer for (int i = 1; i <= n; i++) loop runs once per row and ends with System.out.println() to advance to the next line.
  2. Write a Mini Algebraic Table for Leading Spaces and Symbols: For rows i = 1, 2, 3, ..., write down how many leading spaces s(i) and printable symbols c(i) belong on that row. Look for constant counts (rectangles), linear growth (i), linear shrinking (n - i + 1), or odd progression (2 * i - 1).
  3. Translate Boundary Conditions Into Boolean Tests: For hollow shapes, cross patterns, or checkerboards, combine row index i and column index j with logical OR conditions such as i == 1 || i == n || j == 1 || j == cols. Inside interviews, remember that calling System.out.print() inside tight O(n²) nested loops incurs console I/O overhead on each character—you can optimize large grids to fewer I/O calls using a StringBuilder per row.

Walkthrough Tips for Core Star Patterns (1–7)

When studying the seven foundational patterns below, focus on how the inner loop limit changes as i increments:

  • Square & Rectangle Patterns (Examples 1–2): Both rows and columns stay constant across iterations, teaching you basic 2D grid traversal (i rows × j columns).
  • Right & Inverted Right Triangles (Examples 3–4): Linking the inner upper bound directly to i (j <= i) produces a growing triangle, while inverting the outer or inner range (n - i + 1) flips it cleanly upside down.
  • Centered Pyramid, Inverted Pyramid & Diamond (Examples 5–7): Adding a dedicated leading-space loop (1 to n - i) before the star loop aligns the odd counts 1, 3, 5, 7, ... (2 * i - 1) around a central axis. Stacking a pyramid and inverted pyramid—while skipping the duplicated middle row—produces a clean diamond.

Basic Java Star Patterns

1. Square Pattern

java
for(int i=1;i<=5;i++){
    for(int j=1;j<=5;j++){
        System.out.print("* ");
    }
    System.out.println();
}

Output:

text
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

2. Rectangle Pattern

java
for(int i=1;i<=4;i++){
    for(int j=1;j<=6;j++){
        System.out.print("* ");
    }
    System.out.println();
}

Output:

text
* * * * * *
* * * * * *
* * * * * *
* * * * * *

3. Right Triangle Pattern

java
for(int i=1;i<=5;i++){
    for(int j=1;j<=i;j++){
        System.out.print("* ");
    }
    System.out.println();
}

Output:

text
*
* *
* * * *
* * * * *

4. Inverted Right Triangle

java
for(int i=5;i>=1;i--){
    for(int j=1;j<=i;j++){
        System.out.print("* ");
    }
    System.out.println();
}

Output:

text
* * * * *
* * * *
* *
*

Intermediate Java Star Patterns

5. Pyramid Pattern

java
for(int i=1;i<=5;i++){

    for(int s=1;s<=5-i;s++)
        System.out.print(" ");

    for(int j=1;j<=2*i-1;j++)
        System.out.print("*");

    System.out.println();
}

Output:

text
    *
   ***
  *****
 *******
*********

This pattern combines spaces and stars, making it excellent practice for nested loops.

6. Inverted Pyramid

java
for(int i=5;i>=1;i--){

    for(int s=1;s<=5-i;s++)
        System.out.print(" ");

    for(int j=1;j<=2*i-1;j++)
        System.out.print("*");

    System.out.println();
}

Output:

text
*********
 *******
  *****
   ***
    *

7. Diamond Pattern

A diamond combines a pyramid and an inverted pyramid.

Upper half:

java
for(int i=1;i<=5;i++){

    for(int s=1;s<=5-i;s++)
        System.out.print(" ");

    for(int j=1;j<=2*i-1;j++)
        System.out.print("*");

    System.out.println();
}

Lower half:

java
for(int i=4;i>=1;i--){

    for(int s=1;s<=5-i;s++)
        System.out.print(" ");

    for(int j=1;j<=2*i-1;j++)
        System.out.print("*");

    System.out.println();
}

Output:

text
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

8. Hollow Square Pattern

Hollow patterns print stars only on the outer boundary (i == 1, i == n, j == 1, or j == n) and spaces inside.

java
int n = 5;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++) {
        if (i == 1 || i == n || j == 1 || j == n) {
            System.out.print("* ");
        } else {
            System.out.print("  ");
        }
    }
    System.out.println();
}

Output:

text
* * * * * 
*       * 
*       * 
*       * 
* * * * * 

9. Hollow Rectangle Pattern

Use different limits for rows and cols to draw a hollow frame of arbitrary width.

java
int rows = 4, cols = 7;
for (int i = 1; i <= rows; i++) {
    for (int j = 1; j <= cols; j++) {
        if (i == 1 || i == rows || j == 1 || j == cols) {
            System.out.print("* ");
        } else {
            System.out.print("  ");
        }
    }
    System.out.println();
}

Output:

text
* * * * * * * 
*           * 
*           * 
* * * * * * * 

10. Hollow Right Triangle Pattern

Print a star only on the left edge (j == 1), bottom edge (i == n), or hypotenuse (j == i).

java
int n = 5;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        if (j == 1 || i == n || j == i) {
            System.out.print("* ");
        } else {
            System.out.print("  ");
        }
    }
    System.out.println();
}

Output:

text
* 
* * 
*   * 
*     * 
* * * * * 

11. Hollow Pyramid Pattern

Combine leading space indentation with a boundary check across 2 * i - 1 width positions.

java
int n = 5;
for (int i = 1; i <= n; i++) {
    for (int s = 1; s <= n - i; s++) {
        System.out.print(" ");
    }
    for (int j = 1; j <= 2 * i - 1; j++) {
        if (j == 1 || j == 2 * i - 1 || i == n) {
            System.out.print("*");
        } else {
            System.out.print(" ");
        }
    }
    System.out.println();
}

Output:

text
    *
   * *
  *   *
 *     *
*********

12. Hollow Diamond Pattern

Stack an upper hollow pyramid and a mirrored lower hollow pyramid without printing stars inside the interior.

java
int n = 5;
for (int i = 1; i <= n; i++) {
    for (int s = 1; s <= n - i; s++) System.out.print(" ");
    for (int j = 1; j <= 2 * i - 1; j++) {
        System.out.print((j == 1 || j == 2 * i - 1) ? "*" : " ");
    }
    System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
    for (int s = 1; s <= n - i; s++) System.out.print(" ");
    for (int j = 1; j <= 2 * i - 1; j++) {
        System.out.print((j == 1 || j == 2 * i - 1) ? "*" : " ");
    }
    System.out.println();
}

Output:

text
    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *

Symmetric & Mirrored Star Patterns

13. Butterfly Star Pattern

Each row prints i left stars, 2 * (n - i) center spaces, and i right stars—growing until row n and mirroring back down.

java
int n = 4;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) System.out.print("*");
    for (int s = 1; s <= 2 * (n - i); s++) System.out.print(" ");
    for (int j = 1; j <= i; j++) System.out.print("*");
    System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
    for (int j = 1; j <= i; j++) System.out.print("*");
    for (int s = 1; s <= 2 * (n - i); s++) System.out.print(" ");
    for (int j = 1; j <= i; j++) System.out.print("*");
    System.out.println();
}

Output:

text
*      *
**    **
***  ***
********
***  ***
**    **
*      *

14. Sandglass (Hourglass) Star Pattern

Start with an inverted pyramid of width n down to 1, then reflect it upward back to width n.

java
int n = 5;
for (int i = 0; i < n; i++) {
    for (int s = 0; s < i; s++) System.out.print(" ");
    for (int j = 0; j < n - i; j++) System.out.print("* ");
    System.out.println();
}
for (int i = n - 2; i >= 0; i--) {
    for (int s = 0; s < i; s++) System.out.print(" ");
    for (int j = 0; j < n - i; j++) System.out.print("* ");
    System.out.println();
}

Output:

text
* * * * * 
 * * * * 
  * * * 
   * * 
    * 
   * * 
  * * * 
 * * * * 
* * * * * 

15. Right Pascal's Triangle

Grow a left-aligned triangle from 1 to n stars, then shrink from n - 1 back to 1.

java
int n = 4;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) System.out.print("* ");
    System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
    for (int j = 1; j <= i; j++) System.out.print("* ");
    System.out.println();
}

Output:

text
* 
* * 
* * * 
* * * * 
* * * 
* * 
* 

Number and Character Pattern Programs in Java

Once you master star coordinates, replacing "*" with the column index j, an incrementing counter, binomial coefficients, or ASCII char values unlocks number and alphabet patterns immediately.

16. Number Increasing Triangle & Floyd's Triangle

Using a running counter (num++) across rows produces Floyd's Triangle, a classic beginner interview exercise.

java
int n = 5, num = 1;
for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= i; j++) {
        System.out.print(num++ + " ");
    }
    System.out.println();
}

Output:

text
1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 

17. Pascal's Triangle

Each value in row i is computed iteratively from the previous binomial coefficient via value = value * (i - j) / (j + 1).

java
int n = 5;
for (int i = 0; i < n; i++) {
    for (int s = 1; s < n - i; s++) System.out.print(" ");
    int value = 1;
    for (int j = 0; j <= i; j++) {
        System.out.print(value + " ");
        value = value * (i - j) / (j + 1);
    }
    System.out.println();
}

Output:

text
    1 
   1 1 
  1 2 1 
 1 3 3 1 
1 4 6 4 1 

18. Alphabet Triangle & Continuous Character Pattern

Cast integer offsets from 'A' back to char ((char) ('A' + j) for repeating letters per row, or increment ch++ for continuous sequences).

java
int n = 5;
for (int i = 1; i <= n; i++) {
    for (int j = 0; j < i; j++) {
        System.out.print((char) ('A' + j) + " ");
    }
    System.out.println();
}

Output:

text
A 
A B 
A B C 
A B C D 
A B C D E 

Pattern Coordinate Formula Cheat Sheet

Pattern CategoryOuter Loop (i)Leading SpacesStars / Condition
Square / Rectangle1 to rows01 to cols
Right Triangle1 to n01 to i
Inverted Trianglen down to 101 to i
Centered Pyramid1 to nn - i2 * i - 1
Hollow Boundary1 to nOptional n - ii == 1, i == n, j == 1, or j == cols
Butterfly / Sandglass1..n + n-1..12 * (n - i) or i - 1Upper half mirrored by lower loop
💡
Pro Tip: Before writing a single for loop, draw a quick row-by-column index grid (i for row, j for column) on paper. When you write down the exact count of leading spaces and stars for rows 1, 2, and 3, the algebraic loop formula writes itself.

Test Your Java Foundations

Ready to put nested loops, arrays, and core Java syntax into practice? Take our interactive quiz below before continuing to the exercises:

Common Mistakes Beginners Make

Most bugs in pattern programs come from a handful of off-by-one and formatting slips:

  • Failing to reset inner loop counters: Reusing a while counter outside the inner loop without resetting it back to 1 on every row.
  • Swapping row and column bounds: Confusing i (row index) with j (column index) in hollow or diagonal boundary checks.
  • Misaligning leading spaces: Printing too few or too many spaces before stars, which skews pyramids and diamonds.
  • Calling println() inside the inner loop: Printing a newline after every star instead of once per row.
  • Inconsistent spacing between stars: Mixing "*" and "* " widths without adjusting space padding to match.

Sketching the first three rows on paper eliminates almost all of these mistakes before you compile.

Tips for Mastering Pattern Programming

Build lasting intuition faster by applying these habits:

  • Think in rows first: Count total horizontal lines to lock down your outer loop range (1 to n).
  • Count columns per row: Write down how many symbols appear on rows 1, 2, and 3 to spot linear or odd progressions.
  • Separate spaces from stars: Complex centered shapes become straightforward when you treat leading spaces as their own inner loop.
  • Practice in short daily bursts: Solving two unfamiliar patterns a day builds stronger loop fluency than cramming twenty at once.
  • Mutate solved patterns: Convert a triangle into an inverted triangle, turn a pyramid into a diamond, or swap stars for numbers and characters to test whether you understand the underlying math.

Practice Exercises

Now that you have seen the core code for hollow shapes, symmetric butterflies, Floyd's Triangle, and Pascal's Triangle, test your understanding by writing these variations from scratch without peeking:

  1. Zigzag Star Pattern across 3 diagonal waves ((i + j) % 4 == 0 logic)
  2. Hollow Butterfly Pattern combining inner boundary checks with mirrored spacing
  3. Diamond Number Palindrome (1, 121, 12321) centered with leading spaces
  4. Continuous Character Pyramid iterating 'A' through 'O' row by row
  5. Cross / X-Star Matrix printing stars strictly along i == j and i + j == n + 1

For further problem-solving practice, explore our JavaScript Fundamentals Guide, Algorithms Explained Guide, or challenge yourself in the NeuraQuiz Question Bank.

Advantages of Learning Pattern Programming

Working through pattern exercises delivers compounding payoffs as you advance in Java:

  • Strengthens algorithmic decomposition and loop tracing
  • Sharpens off-by-one debugging instincts
  • Makes nested iteration second nature
  • Builds confidence ahead of university exams and coding interviews
  • Prepares you directly for 2D arrays, matrices, and dynamic programming grids

Resources for Continued Learning

For deeper coverage of Java control flow, arrays, and standard library APIs, explore the official Oracle Java Tutorials and the Dev.java Language Basics documentation.

Frequently Asked Questions

1. Why are Java star patterns important?

They improve logical thinking, strengthen loop concepts, and prepare beginners for algorithm-based programming.

2. Which Java concept is most important for star patterns?

Nested for loops are the foundation of almost every star pattern.

3. Are star patterns asked in coding interviews?

Yes. Many beginner and entry-level technical interviews include pattern programming questions to evaluate logical reasoning.

4. How long does it take to master pattern programming?

With consistent practice for 20–30 minutes a day, most beginners become comfortable within a few weeks.

5. Should I memorize every pattern?

No. Understanding the row-column relationship is much more valuable than memorizing code.

6. Can star pattern logic help with data structures and algorithms?

Absolutely. The ability to analyze loops, conditions, and iteration transfers directly to arrays, matrices, recursion, and many algorithmic problems.

Conclusion

Mastering Java star patterns is one of the highest-return exercises you can do early in your programming journey. Each square, triangle, pyramid, hollow frame, and symmetric shape sharpens your mental model of nested loops, boundary conditions, and algorithmic structure.

Once you can derive row-and-column formulas on paper and translate them cleanly into Java code, you will find matrices, two-pointer array traversal, recursion, and dynamic programming grids far easier to tackle. Keep practicing a couple of variations daily and test your Java fundamentals regularly to lock in that fluency.

Interactive Skill Check

Ready to test your Java knowledge?

Put what you just read into practice with timed scenario questions and instant explanations.