Java Hollow Square Pattern (Border of 1s)

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

What Is This Pattern?

A hollow square of 1s prints a border of ones with empty space inside — top and bottom rows are full; middle rows have ones only at the edges.

Remember
Rule: for each cell (i, j),
      print "1 " on the border, "  " inside

1 1 1 1 1
1       1
1       1
1       1
1 1 1 1 1     ← rows = 5

Unlike Program 41 (square number pyramid), here every cell is either a border 1 or an inner space.

How to Solve It

Visit every cell in an n × n grid; print "1 " on the border and " " inside.

MethodIdeaBest for
Boundary checki==1 || i==rows || j==1 || j==rows → print 1Learning, interviews, exams
Filled squareSkip the if; always print "1 "When you want a solid block of ones

Pseudocode

Pseudocode
for i from 1 to rows:
    for j from 1 to rows:
        if i is 1 or i is rows or j is 1 or j is rows:
            print "1 "
        else:
            print "  "
    print newline

Cheat sheet

GoalPattern
Walk rowsfor (int i = 1; i <= rows; i++)
Walk columnsfor (int j = 1; j <= rows; j++)
Border testi == 1 || i == rows || j == 1 || j == rows
Print cellSystem.out.print("1 "); or " "
End the rowSystem.out.println();

Printing Numbers vs Starting a New Line

APIEffectUse for
System.out.printStays on the same lineEach cell ("1 " or " ")
System.out.printlnEnds the current lineAfter the column loop finishes

Print values without a newline, then end the row once.

Live Preview

Change the size and the hollow square updates instantly.

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

Live result size = 5 · 25 cells
1 1 1 1 1 
1       1 
1       1 
1       1 
1 1 1 1 1 

Worked Walkthrough — rows = 5, row i = 3

Trace one middle row to see which cells are border ones vs inner spaces.

jBorder?Printed
1Yes (j == 1)1
2No
3No
4No
5Yes (j == rows)1

Row 3 becomes 1 1. Top and bottom rows print 1 for every column.

Java Programs

Three complete programs: fixed rows = 5, Scanner input, and a filled square. Use View Output to reveal sample results.

Example 1 — Fixed rows = 5

Hard-coded size — border check decides each cell.

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

1. Grid loops. Outer i is the row; inner j is the column.

2. Border test. Top, bottom, left, or right → print "1 ".

3. Inner cells. Everything else prints " " to keep columns aligned.

When i = 1: five ones. When i = 3: ones only at j = 1 and j = 5.

Example 2 — Size Input

Read rows at runtime. Same border-check core.

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();
        if (rows < 1) return;

        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

1. Prompt and guard. Read rows; exit early if it is less than 1.

2. Same core. Only the source of rows changes from a literal to user input.

3. Safer input tip. Prefer:

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

Example 3 — Filled Square

Drop the border check — every cell prints "1 ".

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

1. Same grid. Still n × n nested loops.

2. No if. Every cell is "1 " — a solid block.

3. Compare tip. Put Examples 1 and 3 side by side to see what the border check changes.

Edge Cases & Pitfalls

Check these before calling the solution done.

println inside

Column of cells

If println is inside the column loop, each cell lands on its own line. Use print for cells; println only after the row.

Wrong spaces

Broken columns

Inner cells must use " " (two spaces) to match the width of "1 ".

Miss a side

Open border

Forgetting j == 1 or j == rows leaves the left or right edge empty.

No println

One long line

Forgetting println() after the row glues every cell onto one endless line.

rows = 1

Single cell

Output is just 1 — a 1×1 border square.

Bad input

Use hasNextInt

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

Time and Space Complexity

ProgramTimeExtra space
Hollow / filled square (Examples 1–3)O(n²)O(1)

Both loops visit all n × n cells once. Only loop counters are stored.

Key Takeaways

  • Rule: print "1 " on the border; print " " inside.
  • Border test: i==1 || i==rows || j==1 || j==rows.
  • Break the row: call println only after the column loop.
  • Complexity: O(n²) time; O(1) extra space.

One line: for each cell, print "1 " if it is on the border, else " ", then println() after each row.

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.

Next: Right-Aligned Increasing Triangle

Move on to the right-aligned increasing 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