Hollow Square Border Number Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Border Edge Logic

What You’ll Learn

The hollow square border prints numbers only on the edges of a grid — interior cells are spaces. For size = 5: top row 1 2 3 4 5, right column 6..9, bottom row counts down, left column counts down. Separate counters k, l, m handle each edge. This tutorial covers border conditions, live preview, worked Java examples, edge cases, and O(n²) complexity.

Top Row

i == 1

When i == 1, print column number j — gives 1 2 3 4 5.

Right Column

j == size, k++

When j == size (not top row), print and increment k6 7 8 9.

Bottom & Left

l--, m--

Bottom row (i == size) uses l--; left column (j == 1) uses m--.

Hollow Interior

spaces

All non-border cells print three spaces — creates the hollow square look.

Live Preview

3–8 size

Pick grid size and draw the hollow square border instantly in the browser.

O(n²)

Complexity

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

Introduction

A hollow square border prints numbers on the frame only — top, right, bottom, and left edges each use their own counter logic.

In Java: nested loops over i and j, check border with if-else chain, use System.out.format("%-3d", ...) for alignment, then println().

📝 Problem & Approach

Given size = 5, print a 5×5 grid with numbers on the border only.

Java
// size = 5 (conceptual output)
// 1  2  3  4  5
// 16          6
// 15          7
// 14          8
// 13 12 11 10 9

Inputs & Outputs

ItemTypeDescription
nintGrid dimension — typically size ≥ 3 for a visible hollow interior.
i, j, kintRow i; column j; edge counters k, l, m.
Printed outputtextsize × size grid; numbers on border only; spaces inside.

Minimal workflow

Pseudocode
for i from 1 to size:
    for j from 1 to size:
        if i==1: print j
        else if j==size: print k++
        else if i==size: print l--
        else if j==1: print m--
        else: print spaces
    newline

Approach comparison

ApproachIdeaBest for
Nested i-j loopsBorder if-else chain per cellHollow square frame
Simple border checkSimple border boolean checkSequential border counter — Example 3
Scanner inputsc.nextInt() for sizeUser-chosen grid size
Fixed-width formatSystem.out.format("%-3d", value) keeps columns alignedTwo-digit border numbers — all examples

⚡ Quick Reference

GoalPattern
Set sizeint size = 5;
Outer loopfor (i = 1; i <= size; i++)
Top rowif (i == 1) format("%-3d", j)
Right columnelse if (j == size) format("%-3d", k++)
Bottom rowelse if (i == size) format("%-3d", l--)
Left columnelse if (j == 1) format("%-3d", m--)
Skip duplicate middleSystem.out.println(); after inner loop completes
Program 58 contrastHollow diamond uses edge loops per row; this pattern uses a 2D grid with four edge counters

📋 Four Border Edges

How top, right, bottom, left edges and interior spaces work together.

Top row
if (i == 1)
  format("%-3d", j)

Prints 1 through size left to right.

Right column
else if (j == size)
  format("%-3d", k++)

Increments k down the right edge.

Bottom & left
i==size → l--
j==1 → m--

Bottom and left edges count downward.

Learning tip
if order matters

Check top row first — corners belong to top/bottom conditions.

Context

When This Pattern Shows Up

Reach for this pattern when teaching border conditions, grid loops, and formatting.

  1. First lab exercise

    Classic follow-up after hollow pyramids — introduces four-edge border printing on a grid.

  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 58 (hollow diamond), then continue to Program 60 digit-removal pattern.

  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 border logic, grid traversal, and O(n²) thinking.

🔮 Live Preview

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

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

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed size = 5, Scanner input, and a simple sequential-border variant. Click View Output to reveal sample console results.

📚 Getting Started

Print a 5×5 hollow frame — top row shows 1 2 3 4 5.

Example 1 — Fixed size = 5

Hard-coded 5×5 grid — counters k=6, l=13, m=16 with border if-else chain and %-3d formatting.

Java
public class HollowSquareBorder {
    public static void main(String[] args) {
        int k = 6, l = 13, m = 16;

        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                if (i == 1)
                    System.out.format("%-3d", j);
                else if (j == 5)
                    System.out.format("%-3d", k++);
                else if (i == 5)
                    System.out.format("%-3d", l--);
                else if (j == 1)
                    System.out.format("%-3d", m--);
                else
                    System.out.print("   ");
            }
            System.out.println();
        }
    }
}

How It Works

Top row prints 1..5. Right column increments k. Bottom row decrements l. Left column decrements m. Interior prints spaces.

📈 Practical Variant

Read size with Scanner for flexible grid dimension.

Example 2 — Scanner Input

Generalized border logic; counters computed from grid size.

Java
import java.util.Scanner;

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

        int k = size + 1, l = 3 * size - 2, m = 4 * size - 4;

        for (int i = 1; i <= size; i++) {
            for (int j = 1; j <= size; j++) {
                if (i == 1) System.out.format("%-3d", j);
                else if (j == size) System.out.format("%-3d", k++);
                else if (i == size) System.out.format("%-3d", l--);
                else if (j == 1) System.out.format("%-3d", m--);
                else System.out.print("   ");
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

Same border logic as Example 1; grid size comes from Scanner input.

⚡ Simple Variant

Boolean border check with one sequential counter — easier logic, different number sequence.

Example 3 — Sequential Border Counter

Uses border = (i==1 || i==size || j==1 || j==size) and a single incrementing counter.

Java
public class HollowSquareBorderSimple {
    public static void main(String[] args) {
        int size = 5;
        int val = 1;

        for (int i = 1; i <= size; i++) {
            for (int j = 1; j <= size; j++) {
                boolean border = (i == 1 || i == size || j == 1 || j == size);
                if (border) System.out.format("%-3d", val++);
                else System.out.print("   ");
            }
            System.out.println();
        }
    }
}

How It Works

One counter walks the border clockwise — simpler code but a different layout than Example 1.

🧠 How the Algorithm Fills Each Cell

1

Set up grid

Set size = 5 and initialize k=6, l=13, m=16. Nested loops scan every cell.

Setup
2

Top row

When i == 1, print j — top edge reads 1 2 3 4 5.

Top
3

Right column

When j == size, print and increment k — right edge 6 7 8 9.

Right
4

Bottom & left

Bottom row uses l--; left column uses m--; interior prints three spaces.

Edges
=

Hollow square border complete

Visits size² cells (e.g. 25 when size=5) — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — cell i = 3, j = 3, size = 5

Trace interior cell (3,3) — not on any border edge, so it prints spaces.

PhaseCheckResult
Border checki=3,j=3 — not i==1, j!=size, i!=size, j!=1not border
Interiorelse branchprints three spaces

Cell (3,3) stays hollow. Then the inner loop continues to the next column.

Use Cases

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

1. Teaching Border Edge Logic

Clearest visual proof that outer and inner bounds interact.

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

2. Grid Traversal

Nested i-j loops visit every cell — classic 2D grid pattern.

Example: trace size=5 — cell (3,3) is interior, prints spaces.

3. Console Formatting Drills

Practice format("%-3d") for fixed-width column alignment.

Example: compare Example 1 vs Example 3 border layouts.

4. Border Formatting

Use %-3d so two-digit border numbers stay column-aligned.

Example: row 1 prints 1..5; row 5 prints 13..9 in reverse.

5. Complexity Intuition

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

Example: count cells → 5×5 = 25 visits for size=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

    The hollow frame appears immediately — top row, side columns, and bottom row form a clear square border.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Change size, use Scanner, try Example 3 simple border, or continue to Program 60.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the four-edge if-else chain first; then try Scanner input and the simple border variant in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Variables Clearly

    Use size for grid dimension and i/j/k/l/m for loop and counter 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. Check Border Edges in Order

    Test top row first, then right column, bottom row, left column — else print spaces for interior cells.

  5. 5. Dry-Run One Small Row Count

    Trace size = 5 on paper — expect cell (3,3) to print spaces.

Pro Tip: if corner numbers look wrong, check whether i == 1 is tested first.

Common Pitfalls

Mistakes that commonly break hollow square border number patterns.

  1. 1. println() Inside an Inner Loop

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

    → Use print or format inside the inner loop; println() only after each row completes.

  2. 2. Wrong if-else Order

    Checking j == size before i == 1 misplaces corner numbers.

    → Check top row (i == 1) first — corners belong to top/bottom edges.

  3. 3. Forgetting the Row Break

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

    → Always call System.out.println() after the inner j loop completes.

  4. 4. Forgetting Fixed Width

    Printing without %-3d misaligns columns when numbers reach two digits.

    → Use System.out.format("%-3d", value) for consistent column width.

  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 size breaks dynamic input.

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

Edge Cases

Check these inputs before calling the solution done.

size = 1

Single cell

Output is one number: 1 — all four edges collapse onto the same cell.

size = 0

Empty pattern

Loop never runs — print nothing or show a message.

Negative

size < 0

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

Large size

Large size

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

Bad input

Non-numeric Scanner input

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

size = 2

Minimal square

A 2×2 grid has no interior — every cell is on the border.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Change size

  • Try size = 3, 4, or 6
  • Verify interior cell (3,3) prints spaces for size=5

2. Compare variants

  • Run Example 1 vs Example 3 side by side
  • Notice different number sequences on the border

3. Skip interior branch

  • Remove the else spaces branch
  • Observe filled interior instead of hollow

4. Next in series

  • Continue with Program 60 digit-removal pattern
  • Try size=6 and verify interior cells are spaces

Notes

  • Cell count. Grid is size×size; only border cells print numbers.
  • print stays on the line; println advances — mix them carefully.
  • Validate size > 0 for interactive programs; size = 1 prints one digit where all edges overlap.
  • Row logic: if-else chain — top → right → bottom → left → spaces.

Quick Takeaway: nested i,j loops; border if-else; %-3d on edges; spaces inside; then println().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Fixed size = 5 (Example 1)O(n²)O(1)
Scanner input (Example 2)O(n²)O(1)
Simple border (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The hollow square border uses four edge counters on a 2D grid — a natural step after hollow diamond patterns in Program 58. Master the fixed-size version first, then try Scanner input and the simple border variant in Example 3.

Practice the three examples above, then continue to Program 60 for the digit-removal number pattern.

Check border edges in order — print spaces for interior cells — one println() per row.

💡 Best Practices

✅ Do

  • Explain top, right, bottom, left border checks before coding
  • Nested i-j loops; if-else for each edge; spaces inside; then println()
  • Validate size ≥ 3 for interactive programs
  • Check Scanner return value before using size
  • State O(n²) time when asked about complexity

❌ Don’t

  • Skip interior space branch
  • Print without %-3d (columns misalign)
  • Hard-code 5 instead of variable size
  • Ignore bad console input in user-facing demos
  • Skip the size = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this hollow square border number pattern

Four edges use separate counters; interior stays hollow with spaces.

5
Core concepts
02

Nested loops

i,j = 1..size

Code
03

Edge counters

k++, l--, m--

Logic
n 04

Row length

size cols/row

I/O
O 05

Complexity

O(n²)

Analysis

❓ Frequently Asked Questions

Numbers only on the border of a square grid — interior cells are spaces creating a hollow frame.
Each edge continues the sequence differently: k increments on the right, l and m decrement on bottom and left edges.
Fixed-width formatting keeps columns aligned when numbers reach two digits.
Yes. Generalize with k=n+1, l=3n-2, m=4n-4 — see Example 2.
Example 3 uses a simple border check and one counter — easier but a different number sequence.
Non-border cells print three spaces — that creates the hollow interior.
O(n²) for an n×n grid because every cell is visited once.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.

Did you Know? 🔊

Numbers print only on the border of a 5×5 grid: top row 1..5, right column 6..9, bottom row 13..9, left column 16..14 — interior cells are spaces.

Continue to Program 60

Move on to the digit-removal number pattern in the Java number-pattern series.

Program 60 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