Java ProgramsPatternsPrint Diamond Pattern

Print Diamond Pattern in Java

intermediate·  Patterns  ·  Star Patterns

Problem

A diamond is nothing more than a centered pyramid immediately followed by that same pyramid's rows in reverse, minus the shared middle row — the two halves mirror each other around the widest line.

Given a height n, print a diamond of stars n rows tall on top and n minus one rows tall on the bottom.

Input
n = 5
Output
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Java Program

Java
public class DiamondPattern { static void printRow(int n, int i) { StringBuilder row = new StringBuilder(); for (int s = 0; s < n - i; s++) row.append(" "); for (int j = 1; j <= 2 * i - 1; j++) { if (j > 1) row.append(" "); row.append("*"); } System.out.println(row); } public static void main(String[] args) { int n = 5; for (int i = 1; i <= n; i++) printRow(n, i); for (int i = n - 1; i >= 1; i--) printRow(n, i); // mirrors the top half, skipping the widest row } }

Output

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

Core Logic

Pulling the pyramid's row-printing logic out into its own method lets the same code build both halves of the diamond, just called in a different order for each.

How It Works
  1. 1printRow(n, i) prints a single centered row — n - i leading spaces followed by 2i - 1 stars — exactly the pyramid pattern's row logic.
  2. 2The top half calls printRow(n, i) for i from 1 to n, building the pyramid as usual.
  3. 3The bottom half calls the same method for i from n - 1 down to 1, mirroring the top half without its widest row repeated.
  4. 4Reusing one method for both halves means the diamond's shape can never drift out of sync with itself.
For n = 5, the widest row (i = 5, 9 stars) appears exactly once, with 4 shrinking rows above it and 4 shrinking rows below it.
💡

Key Point: The bottom half starts at n - 1, not n — repeating the widest row would leave two identical center lines instead of one sharp point.

Complexity
Time Complexity: O(n²)Space Complexity: O(1)

Why: The diamond visits roughly twice the pyramid's total characters, still proportional to n² overall, with no growing storage.

Key Concepts

helper methodnested for looprow reuse

Related Programs