Hollow Square of 1s Pattern in Java

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Boundary Checks

What You’ll Learn

The hollow square of 1s prints a border of ones with blank space inside. This tutorial covers the border condition, nested loops, a live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Border only

Only first/last row and first/last column print 1; interior cells stay blank.

Column Loop

j = 1..rows

for (j = 1; j <= rows; j++) walks every column in the current row.

Border Check

Four edges

if (i==1 || i==rows || j==1 || j==rows) prints "1 "; otherwise " ".

Outer Loop

Row index i

for (i = 1; i <= rows; i++) walks each row of the square grid.

Live Preview

1–20 rows

Pick a row count and draw the hollow square of 1s instantly in the browser.

O(n²)

Complexity

Visits every cell in an n×n grid — iterations; extra memory stays O(1).

Introduction

A hollow square of 1s prints a border of ones with empty space inside. With rows = 5, the output is a 5×5 grid: full top and bottom rows of ones, and middle rows with ones only at the left and right edges.

In Java you use nested loops over rows and columns, then an if that checks whether the current cell lies on the border. Border cells print "1 "; inner cells print " " to keep columns aligned.

Why it matters?

It teaches boundary detection with a simple condition — a key step before hollow rectangles, frames, and diamonds.

Key Highlights

Nested Grid

Outer loop uses i = 1..rows; inner loop uses j = 1..rows.

Border Condition

First/last row or first/last column → print 1.

Fixed Cell Width

Border uses "1 " and interior uses " " so columns line up.

Series Foundation

Follow Program 41 square pyramid; continue to Program 43 right-aligned triangle.

In short: for each row i and column j, print "1 " on the border and " " inside, then call System.out.println() after each row.

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print an n×n hollow square: border cells show 1, inner cells show spaces.

Java
// rows = 5 (conceptual shape)
// 1 1 1 1 1
// 1       1
// 1       1
// 1       1
// 1 1 1 1 1

Inputs & Outputs

ItemTypeDescription
rowsintNumber of rows (and columns) in the square (typically ≥ 1).
Printed outputtextSquare grid of rows × rows cells; border prints 1, interior prints spaces.

Minimal workflow

Pseudocode
for i from 1 to rows:
    for j from 1 to rows:
        if border cell: print "1 "
        else: print "  "
    print newline

Approach comparison

ApproachIdeaBest for
Border condition1 1 1 1 1 top row, hollow middleLearning and interviews
User-input sizesc.nextInt();Flexible console programs
Filled squareAlways System.out.print("1 ")Contrast with hollow logic

⚡ Quick Reference

GoalPattern
Walk rowsfor (i = 1; i <= rows; i++)
Walk columnsfor (j = 1; j <= rows; j++)
Border checkif (i==1 || i==rows || j==1 || j==rows)
End the rowSystem.out.println();
Program 41 contrastSquare pyramid uses odd widths; this pattern uses a full grid + border test

📋 Border vs Inner vs Combined

Same square cell — how the border check decides between 1 and spaces.

Border check
i==1 || i==rows
|| j==1 || j==rows

True on any edge cell — print "1 "

Inner cells
else branch

Interior positions print " " (two spaces)

Row width
j = 1..rows

Every row has exactly rows cells

Learning tip
trace i=3

Dry-run row 3: 1 at j=1 and j=5, spaces in between

Context

When This Pattern Shows Up

Reach for this pattern when teaching boundary checks inside a full row×column grid.

  1. First lab exercise

    Classic follow-up after centered pyramids and alternating rows.

  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 row count.

  4. Gateway to variants

    Compare with Program 41 (square pyramid), then continue to Program 43 (right-aligned triangle).

  5. Not a UI layout tool

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

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a row count between 1 and 20 and draw the hollow square of 1s in the browser.

Try 5, 7, or 10. Larger values still work up to 20.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Java programs — fixed row count, Scanner input, and a filled-square variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows with two nested loops per line.

Example 1 — Fixed rows = 5

Hard-coded size — nested loops and a border check build each row.

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

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

How It Works

When i = 1, every j hits the border test (top row) — five 1s print. When i = 3, only j = 1 and j = 5 pass the test; the middle columns print spaces.

📈 Practical Variant

Let the user choose the height at runtime.

Example 2 — User Input Version

Read the row count with Scanner.nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class HollowSquareOfOnesInput {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int rows = sc.nextInt();

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

        sc.close();
    }
}

How It Works

Same nested-loop core as Example 1; only the source of rows changes. Non-numeric input throws InputMismatchException with nextInt() — check hasNextInt() for safer labs.

⚡ Readability Variant

Remove the border check to print a completely filled square.

Example 3 — Filled Square

Remove the border if and always print "1 " to get a solid square of ones.

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

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

How It Works

Same nested-loop structure; the inner loop always prints "1 " with no border condition.

🧠 How the Algorithm Prints Rows

1

Set up

System.out is built in; use Scanner when reading input. Set rows (fixed or from input).

Setup
2

Outer loop (rows)

for (i = 1; i <= rows; i++) — walks each row of the square grid.

Row
3

Inner loop (columns)

for (j = 1; j <= rows; j++) visits every column in the current row.

Column
4

Border if / else

Border cells print "1 "; inner cells print " ", then println() ends the row.

Print
=

Hollow border square complete

Total cell visits: O(n²) time, O(1) extra memory.

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

Trace one middle row to see which cells hit the border test.

jBorder?Prints
1yes (j==1)1
2no
3no
4no
5yes (j==rows)1

Row output: 1 1 — total cell visits for the full square: 5×5 = 25 = .

Use Cases

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

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change j <= rows to j <= i and watch the shape change.

2. Pattern Series Base

Foundation for hollow rectangles, diamonds, and framed grids.

Example: add a cols variable for a hollow rectangle.

3. Console Formatting Drills

Practice System.out.print vs row newline without complex math.

Example: put System.out.println() inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: swap 1 for * once the border logic works.

5. Complexity Intuition

Every cell is visited once — n² makes O(n²) concrete for beginners.

Example: count cell visits for n = 5 → 25.

6. Input Validation Labs

Pair the pattern with Scanner and positive-row checks.

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

Pro Tip: when an interviewer asks for patterns, explain the outer/inner 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

    Wrong bounds show up immediately as a misaligned or filled shape.

  2. 2. Minimal Concepts

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

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the border-check version first; then try the filled square in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and keep i/j for row/column — or rename to row/col.

  2. 2. Prefer Scanner

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

  3. 3. Keep System.out.println() Outside

    Only call System.out.println() after the inner loop finishes the row.

  4. 4. Use Ternary for Compact Code

    One-liner: System.out.print(i==1||i==rows||j==1||j==rows ? "1 " : " ");

  5. 5. Dry-Run One Small n

    Trace rows = 3 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of cells per line, you almost certainly put System.out.println() inside the inner loop.

Common Pitfalls

Mistakes that commonly break hollow squares of 1s.

  1. 1. System.out.println() Inside the Inner Loop

    Each cell lands on its own line — you get a column, not a square.

    → Use System.out.print for each cell; System.out.println() only after the inner loop.

  2. 2. Wrong Inner Bound

    Using j <= i instead of j <= rows produces a triangle, not a square.

    → Keep for (j = 1; j <= rows; j++) so every row has the same width.

  3. 3. Forgetting the Row Break

    Omitting System.out.println() glues every cell onto one endless line.

    → Always end the row after the inner loop.

  4. 4. Unchecked Scanner input

    Letters or empty input throw InputMismatchException.

    → Prefer Scanner and re-prompt on failure.

  5. 5. Single Space Inside

    Printing one space instead of two breaks column alignment with border 1 cells.

    → Use " " (two spaces) for inner cells so columns stay aligned.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single cell

Output is just 1 on one line.

rows = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

rows < 0

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

Large n

Many rows

Output grows as n² characters — fine for labs, noisy for huge n.

Bad input

Non-numeric Scanner input

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

Fill char

Filled square

Remove the border if and always print "1 " — see Example 3.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Square number pyramid

2. Right-aligned triangle

  • Increasing numbers aligned to the right
  • Continue with Program 43

3. Hollow rectangle

  • Add a cols variable separate from rows
  • Same border check on four edges

4. Star border

  • Replace "1 " with "* "
  • Keep the same nested-loop structure

Notes

  • Cell count. Total cell visits for an n×n square is — border cells are 4n - 4 when n > 1.
  • print stays on the line; println advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Use "1 " on borders and " " inside so columns stay aligned.

Quick Takeaway: nested row/column loops, border check for edges, fixed-width print tokens, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Filled square (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The hollow square of 1s combines nested loops with a simple border condition — a natural step after centered pyramids. Master the fixed-rows version first, then try user input and the filled square.

Practice the three examples above, then continue to Program 43 for the right-aligned increasing number triangle.

Every row has rows cells — keep println() only after the inner loop finishes.

💡 Best Practices

✅ Do

  • Explain row loop, column loop, and border if before coding
  • Use "1 " / " " and println() after each row
  • Validate rows ≥ 1 for interactive programs
  • Check Scanner return value before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call System.out.println() inside the inner cell loop
  • Skip the border check (you get a filled square instead)
  • Use one space for inner cells when two are needed
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this hollow square of 1s

Print the pattern the beginner-friendly way.

5
Core concepts
02

Border check

Four edge conditions

Code
03

Inner cells

Print two spaces

Logic
n 04

Total visits

n² cells

I/O
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

Only border positions print 1. All inner positions print spaces, so the center stays blank.
It checks i==1 or i==rows (top/bottom) or j==1 or j==rows (left/right). If any is true, it prints 1.
Each cell uses a fixed width so columns align. Border cells use "1 " and inner cells use " ".
Yes. Replace the fixed 5 with a rows variable and read it with Scanner — see Example 2.
Remove the if condition and always print "1 " in the inner loop — see Example 3.
O(n²) for an n×n square because both loops visit every cell once.
Use sc.hasNextInt() before sc.nextInt() so bad input does not throw InputMismatchException.
You get a single "1 " on one line — technically a 1×1 border square.

Did you Know? 🔊

Only border cells print 1 — when i is the first or last row, or j is the first or last column. Inner cells print spaces, which creates the hollow look.

Continue to Program 43

Move on to the right-aligned increasing number triangle in the Java number-pattern series.

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