Print Square Star Pattern in Java
beginner· Patterns · Star Patterns
Problem
A square star pattern is the simplest nested-loop shape — the same fixed number of stars printed on every row, with the outer loop picking the row and the inner loop picking the column.
Given a size n, print a solid n by n square made of stars.
Input
n = 5
Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Java Program
Java
public class SquareStarPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < n; j++) {
if (row.length() > 0) row.append(" ");
row.append("*");
}
System.out.println(row);
}
}
}Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
Core Logic
An outer loop counts the rows, and for every row an inner loop prints the same fixed number of stars — the two loops together cover every position in the grid.
How It Works
- 1The outer
for (int i = 0; i < n; i++)runs once per row. - 2The inner
for (int j = 0; j < n; j++)runs the fullntimes on every row, appending a star each time. - 3A separating space is added before every star except the first in a row, avoiding a trailing space at the end of the line.
- 4Each completed row is printed before the outer loop moves to the next one.
For
n = 5, the inner loop appends 5 stars on every one of the 5 rows, producing a 5-by-5 block.💡
Key Point: Unlike a triangle or pyramid, the inner loop's bound here never depends on the outer loop's counter — every row is identical, which is what makes this the simplest nested-loop pattern to start with.
Complexity
Time Complexity: O(n²)Space Complexity: O(1)
Why: The nested loop visits all n² grid positions, printing one star per position with no growing storage.
Key Concepts
nested for loopouter and inner loopStringBuilder