Print Rhombus Pattern in Java
Problem
A rhombus pattern is a square block of stars that leans to one side, formed by giving every row the same star count but one more leading space than the row before it.
Given a size n, print an n-row rhombus of stars, each row indented one space further than the last.
Java Program
public class RhombusPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
StringBuilder line = new StringBuilder();
for (int j = 1; j < i; j++) line.append(' '); // one more leading space per row
for (int j = 1; j <= n; j++) line.append('*');
System.out.println(line);
}
}
}Output
Core Logic
Keeping every row's star count fixed at n, while increasing only the leading space count row by row, shifts each row further right without changing its shape.
- 1Row
igetsi - 1leading spaces, so row 1 has none and row n has the most. - 2Every row prints the same
nstars, regardless of how many leading spaces came before them. - 3Because only the indentation changes and never the star count, the block's shape stays a perfect parallelogram rather than narrowing or widening.
n = 5, row 3 gets 2 leading spaces then 5 stars, one space further right than row 2's single leading space.Key Point: This differs from a triangle only in what stays fixed — a triangle grows its star count and drops the indentation, while a rhombus grows the indentation and keeps the star count fixed.
Why: Each of the n rows builds a line whose length (spaces plus stars) is proportional to n, so total output scales with n².
Key Concepts
Approach 2: Java 8
import java.util.stream.IntStream;
public class RhombusPatternStream {
public static void main(String[] args) {
int n = 5;
IntStream.rangeClosed(1, n)
.mapToObj(i -> " ".repeat(i - 1) + "*".repeat(n))
.forEach(System.out::println);
}
}
Output
Core Logic
Since every row's shape is just its own leading-space count followed by the same fixed star run, String.repeat() can build each row directly with no inner loop at all.
- 1
IntStream.rangeClosed(1, n)produces one stream element per row numberi. - 2
" ".repeat(i - 1)builds that row's leading spaces directly from the row number. - 3
"*".repeat(n)builds the same fixedn-star run for every row, since the star count never changes. - 4
forEach(System.out::println)prints each completed row as it's produced.
" ".repeat(2) gives two leading spaces, followed by the same five-star run every row has: *****.Key Point: Because the star count is fixed and never depends on the row, no inner stream is even needed here — a single String.repeat() call replaces the entire inner loop.
Why: repeat() still does O(n) work per row to build the spaces and stars, so the total across all n rows remains O(n²).