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

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.
i == 1
When i == 1, print column number j — gives 1 2 3 4 5.
j == size, k++
When j == size (not top row), print and increment k — 6 7 8 9.
l--, m--
Bottom row (i == size) uses l--; left column (j == 1) uses m--.
spaces
All non-border cells print three spaces — creates the hollow square look.
3–8 size
Pick grid size and draw the hollow square border instantly in the browser.
Complexity
Each row scans O(n) positions — total work grows as n².
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().
Given size = 5, print a 5×5 grid with numbers on the border only.
// size = 5 (conceptual output)
// 1 2 3 4 5
// 16 6
// 15 7
// 14 8
// 13 12 11 10 9 | Item | Type | Description |
|---|---|---|
n | int | Grid dimension — typically size ≥ 3 for a visible hollow interior. |
i, j, k | int | Row i; column j; edge counters k, l, m. |
| Printed output | text | size × size grid; numbers on border only; spaces inside. |
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 | Idea | Best for |
|---|---|---|
| Nested i-j loops | Border if-else chain per cell | Hollow square frame |
| Simple border check | Simple border boolean check | Sequential border counter — Example 3 |
| Scanner input | sc.nextInt() for size | User-chosen grid size |
| Fixed-width format | System.out.format("%-3d", value) keeps columns aligned | Two-digit border numbers — all examples |
| Goal | Pattern |
|---|---|
| Set size | int size = 5; |
| Outer loop | for (i = 1; i <= size; i++) |
| Top row | if (i == 1) format("%-3d", j) |
| Right column | else if (j == size) format("%-3d", k++) |
| Bottom row | else if (i == size) format("%-3d", l--) |
| Left column | else if (j == 1) format("%-3d", m--) |
| Skip duplicate middle | System.out.println(); after inner loop completes |
| Program 58 contrast | Hollow diamond uses edge loops per row; this pattern uses a 2D grid with four edge counters |
How top, right, bottom, left edges and interior spaces work together.
if (i == 1)
format("%-3d", j)Prints 1 through size left to right.
else if (j == size)
format("%-3d", k++)Increments k down the right edge.
i==size → l--
j==1 → m--Bottom and left edges count downward.
if order mattersCheck top row first — corners belong to top/bottom conditions.
Reach for this pattern when teaching border conditions, grid loops, and formatting.
Classic follow-up after hollow pyramids — introduces four-edge border printing on a grid.
Outer/inner bound practice with an immediate visual check.
Combine loops with Scanner for a flexible pattern size.
Compare with Program 58 (hollow diamond), then continue to Program 60 digit-removal pattern.
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.
Choose pattern size n and draw the full hollow square border number pattern in the browser.
Three complete Java programs — fixed size = 5, Scanner input, and a simple sequential-border variant. Click View Output to reveal sample console results.
Print a 5×5 hollow frame — top row shows 1 2 3 4 5.
size = 5Hard-coded 5×5 grid — counters k=6, l=13, m=16 with border if-else chain and %-3d formatting.
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();
}
}
} Top row prints 1..5. Right column increments k. Bottom row decrements l. Left column decrements m. Interior prints spaces.
Read size with Scanner for flexible grid dimension.
Generalized border logic; counters computed from grid size.
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();
}
} Same border logic as Example 1; grid size comes from Scanner input.
Boolean border check with one sequential counter — easier logic, different number sequence.
Uses border = (i==1 || i==size || j==1 || j==size) and a single incrementing counter.
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();
}
}
} One counter walks the border clockwise — simpler code but a different layout than Example 1.
Set size = 5 and initialize k=6, l=13, m=16. Nested loops scan every cell.
When i == 1, print j — top edge reads 1 2 3 4 5.
When j == size, print and increment k — right edge 6 7 8 9.
Bottom row uses l--; left column uses m--; interior prints three spaces.
Visits size² cells (e.g. 25 when size=5) — O(n²) time, O(1) extra memory.
i = 3, j = 3, size = 5Trace interior cell (3,3) — not on any border edge, so it prints spaces.
| Phase | Check | Result |
|---|---|---|
| Border check | i=3,j=3 — not i==1, j!=size, i!=size, j!=1 | not border |
| Interior | else branch | prints three spaces |
Cell (3,3) stays hollow. Then the inner loop continues to the next column.
Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.
Clearest visual proof that outer and inner bounds interact.
Example: use Scanner for dynamic size — see Example 2.
Nested i-j loops visit every cell — classic 2D grid pattern.
Example: trace size=5 — cell (3,3) is interior, prints spaces.
Practice format("%-3d") for fixed-width column alignment.
Example: compare Example 1 vs Example 3 border layouts.
Use %-3d so two-digit border numbers stay column-aligned.
Example: row 1 prints 1..5; row 5 prints 13..9 in reverse.
Each row scans O(n) positions — total work grows as n².
Example: count cells → 5×5 = 25 visits for size=5.
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.
Why this pattern earns a permanent spot in beginner Java courses.
The hollow frame appears immediately — top row, side columns, and bottom row form a clear square border.
Only loops and console output — no arrays or math libraries.
Change size, use Scanner, try Example 3 simple border, or continue to Program 60.
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.
Small habits that keep number-pattern code clean.
Use size for grid dimension and i/j/k/l/m for loop and counter variables.
ScannerAvoid crashes when the user types letters instead of a number.
Finish the inner loop for row i, then call println().
Test top row first, then right column, bottom row, left column — else print spaces for interior cells.
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.
Mistakes that commonly break hollow square border number patterns.
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.
Checking j == size before i == 1 misplaces corner numbers.
→ Check top row (i == 1) first — corners belong to top/bottom edges.
Omitting println() after both inner loops glues all rows onto one line.
→ Always call System.out.println() after the inner j loop completes.
Printing without %-3d misaligns columns when numbers reach two digits.
→ Use System.out.format("%-3d", value) for consistent column width.
Letters or empty input throw InputMismatchException.
→ Use sc.hasNextInt() before sc.nextInt().
Using literal 5 in loop bounds instead of variable size breaks dynamic input.
→ Use one size variable for both outer and inner loop bounds.
Check these inputs before calling the solution done.
Output is one number: 1 — all four edges collapse onto the same cell.
Loop never runs — print nothing or show a message.
size < 0Treat as invalid; re-prompt instead of silent empty output.
Large values produce wide rows — fine for labs; use smaller size for quick demos.
Unchecked Scanner leaves size unset — call sc.hasNextInt() first.
A 2×2 grid has no interior — every cell is on the border.
Try these variations to lock in the pattern.
size = 3, 4, or 6print stays on the line; println advances — mix them carefully.size > 0 for interactive programs; size = 1 prints one digit where all edges overlap.Quick Takeaway: nested i,j loops; border if-else; %-3d on edges; spaces inside; then println().
| Program | Time | Extra 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) |
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.
println()size ≥ 3 for interactive programsScanner return value before using size%-3d (columns misalign)sizesize = 1 edge caseFour edges use separate counters; interior stays hollow with spaces.
Grid is size×size
Definitioni,j = 1..size
Codek++, l--, m--
Logicsize cols/row
O(n²)
AnalysisNumbers 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.
Move on to the digit-removal number pattern in the Java number-pattern series.
12 people found this page helpful