Java Hollow Square Number Pattern (Border)

Beginner
6 min read
Updated: Sep 2026
3 programs
Live preview

What Is This Pattern?

A hollow square border prints numbers only on the edges of an n × n grid. Interior cells are spaces — a hollow number frame.

Remember
Rule: print on border only
  top:    1 .. n
  right:  k++   (starts at n+1)
  bottom: l--   (starts at 3n−2)
  left:   m--   (starts at 4n−4)

1  2  3  4  5
16          6
15          7
14          8
13 12 11 10 9     ← n = 5

Order of checks matters: top → right → bottom → left. Corners belong to the first matching edge (top-left/top-right on the top row; bottom-right on the right column).

How to Solve It

Scan every cell; if it is on the border, print the next edge number — otherwise print spaces.

MethodIdeaBest for
Fixed nHard-coded counters for 5×5Labs and demos
Scanner inputCompute k, l, m from nInteractive practice
Sequential counterOne val++ on any border cellSimpler logic (different order)

Pseudocode

Pseudocode
k = n + 1
l = 3*n - 2
m = 4*n - 4

for i from 1 to n:
    for j from 1 to n:
        if i == 1:      print j          // top
        else if j == n: print k; k++     // right
        else if i == n: print l; l--     // bottom
        else if j == 1: print m; m--     // left
        else:           print spaces     // interior
    new line

Cheat sheet

GoalPattern
Set sizeint n = 5;
Start countersk = n+1; l = 3*n-2; m = 4*n-4;
Top / righti == 1 → j; j == n → k++
Bottom / lefti == n → l--; j == 1 → m--
Align columnsSystem.out.format("%-3d", value)
InteriorSystem.out.print(" ") (three spaces)

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.print / formatStays on the same lineEach cell (number or spaces)
System.out.printlnEnds the lineAfter the inner j loop finishes

Build each row with print/format, then break once.

Live Preview

Change n and the hollow square border updates instantly (classic k/l/m sequence).

Whole numbers from 3 to 8. Tap a chip or type a value — the preview redraws as you go.

Live result n = 5 · cells = 25
1  2  3  4  5
16          6
15          7
14          8
13 12 11 10 9

Worked Walkthrough — n = 3

Counters: k = 4, l = 7, m = 8. Trace each row left to right.

Row iWhat printsPrinted row
1Top: 1 2 31 2 3
2Left m--=8, space, right k++=48 4
3Bottom: 7 6 5 (right corner via k)7 6 5

On the last row, the rightmost cell matches j == n first, so it uses k (here 5), then the remaining bottom cells use l--.

Java Programs

Three complete programs: fixed 5×5, Scanner input, and a sequential border counter. Use View Output to reveal sample results.

Example 1 — Fixed n = 5

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

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

1. Top row. When i == 1, print j → 1 2 3 4 5.

2. Right, bottom, left. k++ down the right edge, l-- across the bottom, m-- up the left.

3. Interior. Everything else prints three spaces so columns stay aligned with %-3d.

Example 2 — Scanner Input

Same border logic; compute counters from n at runtime.

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 n = sc.nextInt();
        if (n < 1) return;

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

        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1) System.out.format("%-3d", j);
                else if (j == n) System.out.format("%-3d", k++);
                else if (i == n) 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

1. Formulas. k = n+1, l = 3n−2, m = 4n−4 scale the counters for any size.

2. Same edges. Only the source of n changes — the if-else chain matches Example 1.

3. Safer input tip. Prefer:

Safer input
if (!sc.hasNextInt()) {
    System.out.println("Enter a positive integer.");
    return;
}
int n = sc.nextInt();
if (n < 1) {
    System.out.println("Enter a positive integer.");
    return;
}

Example 3 — Sequential Border Counter

One val++ on any border cell — simpler code, different number order.

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

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

How It Works

1. Border test. i==1 || i==n || j==1 || j==n marks every edge cell.

2. Row-major count. Numbers increase left-to-right, top-to-bottom — not clockwise like Examples 1–2.

3. Same hollow shape. Interior still prints three spaces; only the sequence differs.

Edge Cases & Pitfalls

Check these before calling the solution done.

Wrong order

Corner ownership

Check top → right → bottom → left. Reordering assigns corners to the wrong counter.

Bad counters

Off-by-one edges

Use k=n+1, l=3n−2, m=4n−4. Wrong starts break the continuous sequence.

print vs format

Misaligned columns

Two-digit numbers need %-3d (or matching spaces). Plain print skews the frame.

n = 1

Single cell

Output is just 1 — all four edges collapse onto one cell.

n = 2

No interior

Every cell is on the border — the frame is solid with no hollow middle.

Bad input

Use hasNextInt

nextInt() throws on letters — prefer hasNextInt() and require a positive integer.

Time and Space Complexity

ProgramTimeExtra space
Examples 1–3O(n²)O(1)

You visit every cell of an n × n grid once → O(n²) time and constant extra memory.

Key Takeaways

  • Rule: print numbers on the border only; interior gets spaces.
  • Counters: k=n+1, l=3n−2, m=4n−4 for the classic clockwise sequence.
  • Align: use %-3d (or three spaces) so two-digit numbers stay in columns.
  • Complexity: O(n²) for size n.

One line: walk the square edge by edge with dedicated counters; leave the middle blank.

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 the bottom and left.
Fixed-width formatting keeps columns aligned when numbers reach two digits.
Yes. Use k = n+1, l = 3n−2, m = 4n−4 — see Example 2.
Example 3 uses a simple border check and one counter — easier logic, but a different number order.
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 an n×n grid. For n=5: top 1..5, right 6..9, bottom 13..9, left 16..14 — interior cells are spaces.

Next: Number by Removing Last Digit Each Line

Continue with the digit-removal number pattern in the Java number-pattern series.

Program 60 tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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