Hollow Number Diamond Number Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Top + Bottom Halves

What You’ll Learn

The hollow number diamond prints Program 57’s hollow pyramid for rows 1..n, then mirrors rows n-1..1. For n = 5 you get nine rows forming a symmetric hollow diamond. Same edge logic on every row — two outer loops drive top and bottom halves. This tutorial covers mirroring, live preview, worked Java examples, edge cases, and O(n²) complexity.

Top Half

i = 1..n

First outer loop prints the hollow pyramid — same edge logic as Program 57.

Edge Logic

i==j, i==k

Left loop j=n..1 and right loop k=2..n print row number at edges only.

Bottom Half

i = n-1..1

Second outer loop mirrors rows back down — start at n-1 to skip duplicate middle.

Two Edge Digits

2n-1 cols

Row i spans 2n-1 columns — row number at left and right edges (row 1 overlaps).

Live Preview

3–12 rows

Pick diamond size and draw the hollow diamond instantly in the browser.

O(n²)

Complexity

Each row scans O(n) positions — total work grows as n².

Introduction

A hollow number diamond is Program 57’s hollow pyramid plus a mirrored bottom half. Row 2 reads 2 2; the widest row shows 5 5; then rows shrink back to 1.

In Java: top loop for (i = 1; i <= n; i++), bottom loop for (i = n-1; i >= 1; i--) — each row uses left/right edge loops, then println().

📝 Problem & Approach

Given n = 5, print nine hollow rows — pyramid up, then mirror down.

Java
// n = 5 (conceptual output — 2n-1 = 9 rows)
//     1
//    2 2
//   3   3
//  4     4
// 5       5
//  4     4
//   3   3
//    2 2
//     1

Inputs & Outputs

ItemTypeDescription
nintHalf-height — diamond has 2n-1 rows total (typically n ≥ 1).
i, j, kintRow i; left index j; right index k.
Printed outputtext2n-1 columns per row; 2n-1 rows total; edges only.

Minimal workflow

Pseudocode
for i from 1 to n: print hollow row i
for i from n-1 down to 1: print hollow row i
(each row: left j=n..1, right k=2..n, edge conditions)

Approach comparison

ApproachIdeaBest for
Two outer loopsTop half i=1..n + bottom half i=n-1..1Complete hollow diamond
printRow helperExtract row printing into a methodLess duplicated code — Example 3
Scanner inputsc.nextInt() for nUser-chosen pyramid height
Compact outputStringBuilder joins values with single spacesReusable row builder — Example 3

⚡ Quick Reference

GoalPattern
Set nint n = 5;
Outer loopfor (i = 1; i <= n; i++)
Left loopfor (j = n; j >= 1; j--) print j if i==j else space
Right loopfor (k = 2; k <= n; k++) print k if i==k else space
Bottom halffor (i = n-1; i >= 1; i--) — same row logic, mirror down
Skip duplicate middleSystem.out.println(); after both edge loops per row
Program 57 contrastHollow pyramid is top half only; this diamond mirrors the bottom from n-1 down to 1

📋 Top Half vs Bottom Half

How top half, bottom half, and shared row logic work together.

Top half
for (i = 1; i <= n; i++)
  printRow(i, n)

Hollow pyramid rows 1 through n.

Bottom half
for (i = n-1; i >= 1; i--)
  printRow(i, n)

Mirror back — skip row n to avoid duplicate.

Row builder
j=n..1, k=2..n
i==j or i==k → digit

Same edge logic on every row — Program 57 core.

Learning tip
trace n=5, i=3

Row 3 appears twice — once going up, once mirrored down.

Context

When This Pattern Shows Up

Reach for this pattern when teaching mirroring, diamonds, and nested loops.

  1. First lab exercise

    Classic follow-up after hollow pyramids — introduces top-half + mirrored bottom-half.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with Scanner for a flexible pattern size.

  4. Gateway to variants

    Compare with Program 57 (hollow pyramid), then continue to Program 59 hollow square border.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one program that locks in mirroring, diamond symmetry, and O(n²) thinking.

🔮 Live Preview

Choose pattern size n and draw the full hollow number diamond pattern in the browser.

Try 3, 5, or 8 for n (up to 12).

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed n = 5, Scanner input, and a compact StringBuilder variant. Click View Output to reveal sample console results.

📚 Getting Started

Print nine hollow rows — widest row shows 5 at both edges.

Example 1 — Fixed n = 5

Hard-coded n = 5 — top half i=1..n, bottom half i=n-1..1 — same edge loops per row.

Java
public class HollowNumberDiamond {
    public static void main(String[] args) {
        int n = 5;

        for (int i = 1; i <= n; i++) {
            for (int j = n; j >= 1; j--) {
                if (i == j) System.out.print(j);
                else System.out.print(" ");
            }
            for (int k = 2; k <= n; k++) {
                if (i == k) System.out.print(k);
                else System.out.print(" ");
            }
            System.out.println();
        }

        for (int i = n - 1; i >= 1; i--) {
            for (int j = n; j >= 1; j--) {
                if (i == j) System.out.print(j);
                else System.out.print(" ");
            }
            for (int k = 2; k <= n; k++) {
                if (i == k) System.out.print(k);
                else System.out.print(" ");
            }
            System.out.println();
        }
    }
}

How It Works

First loop builds the hollow pyramid (Program 57). Second loop mirrors from n-1 down — row 5 appears once at the widest point.

📈 Practical Variant

Read n with Scanner for flexible diamond size.

Example 2 — Scanner Input

Same top + bottom diamond logic; half-height comes from user input.

Java
import java.util.Scanner;

public class HollowNumberDiamondInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter n: ");
        int n = sc.nextInt();

        for (int i = 1; i <= n; i++) {
            for (int j = n; j >= 1; j--) {
                if (i == j) System.out.print(j);
                else System.out.print(" ");
            }
            for (int k = 2; k <= n; k++) {
                if (i == k) System.out.print(k);
                else System.out.print(" ");
            }
            System.out.println();
        }

        for (int i = n - 1; i >= 1; i--) {
            for (int j = n; j >= 1; j--) {
                if (i == j) System.out.print(j);
                else System.out.print(" ");
            }
            for (int k = 2; k <= n; k++) {
                if (i == k) System.out.print(k);
                else System.out.print(" ");
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same top + bottom diamond logic as Example 1; half-height comes from Scanner input.

⚡ Compact Variant

Extract row printing into a printRow helper — less duplicated code.

Example 3 — Compact Rows

Extract printRow to avoid duplicating edge loops in top and bottom halves.

Java
public class HollowNumberDiamondCompact {
    public static void main(String[] args) {
        int n = 5;

        for (int i = 1; i <= n; i++) printRow(i, n);
        for (int i = n - 1; i >= 1; i--) printRow(i, n);
    }

    static void printRow(int i, int n) {
        StringBuilder row = new StringBuilder();
        for (int j = n; j >= 1; j--) row.append(i == j ? j : " ");
        for (int k = 2; k <= n; k++) row.append(i == k ? k : " ");
        System.out.println(row);
    }
}

How It Works

One printRow method serves both halves — cleaner and easier to maintain.

🧠 How the Algorithm Builds Each Row

1

Top half loop

Outer loop for (i = 1; i <= n; i++) prints the hollow pyramid — rows 1 through n.

Setup
2

Edge logic per row

Each row: left loop j=n..1, right loop k=2..n — print digit at edges, space elsewhere.

Edges
3

Bottom half loop

Second outer loop for (i = n-1; i >= 1; i--) mirrors rows back down.

Mirror
4

Skip duplicate middle

Start bottom half at n-1, not n — prevents printing the widest row twice.

Break
=

Hollow number diamond complete

Total 2n-1 rows (e.g. 9 when n=5) — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — row i = 3, n = 5

Trace row 3 to see top half reaches row 3, then bottom half mirrors it back.

PhaseLoopRow so far
Top halfi=1..5, row 3 at i=3pyramid grows to widest row
Bottom halfi=4..1, row 3 again at i=3mirror shrinks back to 1

Row 3 appears in both halves. Then println() moves to row 4.

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Top + Bottom Halves

Clearest visual proof that outer and inner bounds interact.

Example: use Scanner for dynamic rows — see Example 2.

2. Diamond Symmetry

Two outer loops share the same row logic — classic mirror pattern.

Example: trace n=5 — 9 total rows, middle row 5 appears once.

3. Console Formatting Drills

Practice println vs print for multi-line vs single-line output.

Example: use StringBuilder for clean rows — see Example 3.

4. Full Diamond

Top pyramid plus mirrored bottom — symmetric hollow diamond.

Example: row 4 appears twice — once ascending, once descending.

5. Complexity Intuition

Each row scans O(n) positions — total work grows as n².

Example: count total rows → 2×5-1 = 9 rows for n=5.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

Example: reject n <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner loop roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner Java courses.

  1. 1. Instant Visual Feedback

    Starting bottom loop at n duplicates the widest row immediately.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Change n, use Scanner, extract printRow, or continue to Program 59.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the top + bottom halves first; then try Scanner input and the printRow helper in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Variables Clearly

    Use n for height and i/j/k for loop variables.

  2. 2. Prefer Scanner

    Avoid crashes when the user types letters instead of a number.

  3. 3. Row Break After Inner Loop

    Finish the inner loop for row i, then call println().

  4. 4. Start Right Loop at k = 2

    Starting at k = 1 duplicates the center on row 1 — use k = 2 to skip overlap.

  5. 5. Dry-Run One Small Row Count

    Trace n = 5 on paper — expect 2n-1 = 9 rows with row 3 appearing twice.

Pro Tip: if the widest row prints twice, check whether the bottom loop starts at n-1.

Common Pitfalls

Mistakes that commonly break hollow number diamond patterns.

  1. 1. println() Inside an Inner Loop

    Each number lands on its own line — you get a vertical stack, not a hollow diamond row.

    → Use print inside left and right edge loops; println() only after they finish.

  2. 2. Starting Bottom Half at n

    Starting bottom loop at i = n prints the widest row twice.

    → Use for (i = n-1; i >= 1; i--) so the middle row is not duplicated.

  3. 3. Forgetting the Row Break

    Omitting println() after both inner loops glues all rows onto one line.

    → Always call System.out.println() after left and right edge loops complete.

  4. 4. Right Loop Starts at k = 1

    Starting at k = 1 duplicates the center digit on row 1 — use k = 2 instead.

    → Right half starts at k = 2 to skip the overlapping center column.

  5. 5. Unchecked Scanner Input

    Letters or empty input throw InputMismatchException.

    → Use sc.hasNextInt() before sc.nextInt().

  6. 6. Hard-coding 5 Everywhere

    Using literal 5 in loop bounds instead of variable n breaks dynamic input.

    → Use one n variable for outer loop and both inner loop bounds.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single line

Output is one line: 1 — right edge overlaps left on the single column.

n = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

n < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Large n

Large values produce wide rows — fine for labs; use smaller n for quick demos.

Bad input

Non-numeric Scanner input

Unchecked Scanner leaves n unset — call sc.hasNextInt() first.

Compact

Single-line form

Use conditional spacing to avoid trailing spaces — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change n

  • Try n = 3, 6, or 8
  • Verify diamond has 2n-1 rows

2. printRow helpers

  • Build each row without trailing spaces
  • Compare print-based vs StringBuilder output

3. Start bottom at n

  • Start bottom at n and see duplicated middle row
  • Observe widest row printed twice

4. Next in series

  • Continue with Program 59 hollow square border
  • Try n=6 and verify 11 total rows (2×6-1)

Notes

  • Cell count. Diamond has 2n-1 rows; widest row appears once when bottom starts at n-1.
  • print stays on the line; println advances — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 prints one digit where edges overlap.
  • Row logic: top half 1..n, bottom half n-1..1 — same row logic both times.

Quick Takeaway: top i=1..n, bottom i=n-1..1; each row uses left/right edge loops; then println().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed n = 5 (Example 1)O(n²)O(1)
Scanner input (Example 2)O(n²)O(1)
Compact rows (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The hollow number diamond combines Program 57’s pyramid with a mirrored bottom half — a natural step after the hollow pyramid in Program 57. Master the fixed-n version first, then try Scanner input and the compact StringBuilder variant in Example 3.

Practice the three examples above, then continue to Program 59 for the hollow square border pattern.

Mirror from n-1 — never duplicate the middle row — one println() per outer iteration.

💡 Best Practices

✅ Do

  • Explain top half, bottom half, and shared edge logic before coding
  • Top loop 1..n, bottom loop n-1..1; same row code both times
  • Validate n ≥ 1 for interactive programs
  • Check Scanner return value before using n
  • State O(n²) time when asked about complexity

❌ Don’t

  • Start bottom half at n
  • Start bottom loop at n (duplicates middle row)
  • Hard-code 5 instead of variable n
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this hollow number diamond pattern

Top half builds pyramid; bottom half mirrors from n-1 down to 1.

5
Core concepts
02

Outer loop

i = 1..n

Code
03

Edge loops

Top 1..n, bottom n-1..1

Logic
n 04

Row length

2n-1 cols/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

Program 57 prints only the top half (hollow pyramid). Program 58 adds a mirrored bottom half to form a complete diamond.
Starting at n would duplicate the widest middle row. n-1 mirrors back without repeating row n.
For size n, the diamond has 2n-1 rows — n rows up, then n-1 rows down.
At i=1, left and right edge positions overlap — only one digit prints.
Yes. Use variable n in both outer loops and all inner bounds.
Second outer loop: for (i = n-1; i >= 1; i--) — never start at n again.
O(n²) because you print 2n-1 rows and each row scans about 2n-1 positions.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Program 57’s hollow pyramid printed once, then mirrored from n-1 down to 1 — that gives a hollow diamond with 2n-1 rows.

Continue to Program 59

Move on to the hollow square border pattern in the Java number-pattern series.

Program 59 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful