Filled Diamond Star Pattern in Java

Beginner
⏱️ 10 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
2*i - 1 stars

What You’ll Learn

A filled diamond is a center-aligned pyramid stacked with its mirror: spaces for centering, odd star counts for symmetry, and a lower half that starts at rows - 1. This tutorial covers the shape rule, both halves, a live preview, algorithm steps, worked Java examples, edge cases, and complexity.

Shape Rule

Pyramid + mirror

Grow to 2*rows-1 stars, then shrink back to 1 — solid stars every row.

Leading Spaces

rows - i

Center each row with rows - i spaces before the stars.

Odd Star Runs

2*i - 1

Print 1, 3, 5, … stars so every row has a single center.

No Duplicate Peak

Start at rows - 1

Lower half begins below rows so the widest line prints once.

Live Preview

1–12 rows

Pick a half-height and draw the solid diamond in the browser.

O(n²)

Complexity

2n - 1 lines, each Θ(n) work — overall O(n²), O(1) extra space.

Introduction

A filled diamond is a solid, center-aligned diamond of * characters. You build it by printing a centered pyramid for i = 1rows, then the same row formula with i running from rows - 1 down to 1.

Unlike the hollow diamond (Program 9), every position in the star segment is filled. Tip rows are shorter; the middle row has 2 * rows - 1 stars and no leading spaces when i == rows.

Why it matters?

It stitches two earlier skills — Program 5’s pyramid and reverse outer iteration — into one figure. Once this clicks, hollow and framed diamonds are smaller jumps.

Key Highlights

Two Phases

Upper 1..rows, then lower rows-1..1.

Same Inners

Spaces then odd star runs — reused in both halves.

Odd Widths

2*i - 1 keeps a centered peak each row.

Solid Fill

Full star segments — not an outline like Program 9.

In short: for each half, print rows - i spaces and 2 * i - 1 stars; grow i to rows, then shrink from rows - 1 to 1.

📝 Problem & Approach

Given a positive integer rows (half-height of the diamond), print a solid center-aligned diamond with 2 * rows - 1 lines.

Java
// rows = 5 (conceptual shape; spaces shown as ·)
// ····*
// ···***
// ··*****
// ·*******
// *********
// ·*******
// ··*****
// ···***
// ····*

Inputs & Outputs

ItemTypeDescription
rowsintHalf-height (number of rows in the upper pyramid, typically ≥ 1).
Printed outputtext2 * rows - 1 centered lines; row formula uses spaces + odd star runs.

Minimal workflow

Pseudocode
for i from 1 to rows:          // upper half
    print (rows - i) spaces
    print (2 * i - 1) stars
    newline

for i from rows - 1 down to 1: // lower half
    print (rows - i) spaces
    print (2 * i - 1) stars
    newline

Approach comparison

ApproachIdeaBest for
Two outer loopsUpper grow + lower shrink, shared innersLearning and interviews
printRow helperBuild spaces and stars as stringsShorter demos after loops click

⚡ Quick Reference

GoalPattern
Leading spacesfor (j = 1; j <= rows - i; j++) System.out.print(" ");
Star runfor (k = 1; k <= 2 * i - 1; k++) System.out.print("*");
Upper halffor (i = 1; i <= rows; i++)
Lower halffor (i = rows - 1; i >= 1; i--)
Total lines2 * rows - 1
Widest stars2 * rows - 1 (when i == rows)

📋 Filled vs Hollow vs Pyramid Alone

Same family of patterns — different fill and loop range.

This page
solid diamond

Full 2*i-1 star runs; tip rows shorter

Program 9
hollow outline

Diagonal stars only; fixed width 2*rows-1

Program 5
upper only

Same inners as this page’s first half

Interview tip
say both halves

Explain grow then shrink — and why skip i == rows twice

Context

When This Pattern Shows Up

Reach for a filled diamond when combining centering with a grow-then-shrink outer sequence.

  1. After pyramids

    Natural next step once Program 5’s centered triangle is solid.

  2. Two-phase loop drills

    Practice ascending then descending outer bounds with shared inners.

  3. Symmetry checks

    Odd star counts and matching space formulas teach left–right balance.

  4. Gateway to hollow / framed

    Programs 9 and 11 reuse the two-phase idea with different fill rules.

  5. Not a graphics API

    Terminal teaching pattern — not how you draw diamonds in UI frameworks.

Key benefit: one figure that combines centering, odd widths, and careful outer-loop sequencing without duplicate middle rows.

🔮 Live Preview

Choose a half-height between 1 and 12 and draw the filled diamond in the browser.

Try 4, 5, or 7. Total printed lines will be 2 * rows - 1.

Live result
Press "Draw diamond".

Examples Gallery

Three complete Java programs — fixed half-height, console input, and a printRow helper. Click View Output to reveal sample console results.

📚 Getting Started

Print a diamond with half-height 5 using classic nested loops.

Example 1 — Fixed rows = 5

Same j / k inner loops as Program 5, plus the mirrored lower half.

Java
public class FilledDiamond {
    public static void main(String[] args) {
        int rows = 5;
        int i, j, k;

        /* Upper half */
        for (i = 1; i <= rows; i++) {
            for (j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        /* Lower half (no duplicate widest row) */
        for (i = rows - 1; i >= 1; i--) {
            for (j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

How It Works

Upper i grows from 1 to 5: spaces shrink, stars grow 1, 3, 5, 7, 9. Lower i shrinks from 4 to 1: spaces grow, stars shrink 7, 5, 3, 1 — closing the diamond without reprinting the middle row.

📈 Practical Variant

Let the user choose the half-height at runtime.

Example 2 — User Input Version

Read rows with Scanner and nextInt() (check hasNextInt() in real apps).

Java
import java.util.Scanner;

public class FilledDiamondInput {
    public static void main(String[] args) {
        int rows;
        int i, j, k;
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the number of rows: ");
        rows = sc.nextInt();

        for (i = 1; i <= rows; i++) {
            for (j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        for (i = rows - 1; i >= 1; i--) {
            for (j = 1; j <= rows - i; j++) {
                System.out.print(" ");
            }
            for (k = 1; k <= 2 * i - 1; k++) {
                System.out.print("*");
            }
            System.out.println();
        }

        sc.close();
    }
}

How It Works

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

⚡ Shortcut Style

Same diamond without explicit inner character loops.

Example 3 — printRow Helper + repeat

Build each row’s margin and star run in one call each.

Java
public class FilledDiamondHelper {
    static void printRow(int rows, int i) {
        System.out.println(" ".repeat(rows - i) + "*".repeat(2 * i - 1));
    }

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

        for (int i = 1; i <= rows; i++) {
            printRow(rows, i);
        }

        for (int i = rows - 1; i >= 1; i--) {
            printRow(rows, i);
        }
    }
}

How It Works

printRow encodes the shared formula once; both outer loops call it. Great after you understand the nested-loop version — keep the explicit j/k loops for exams that want both bounds visible.

🧠 How the Algorithm Prints the Diamond

1

Upper half (i = 1rows)

Print rows - i spaces, then 2 * i - 1 stars, then a newline. Star counts: 1, 3, 5, …, 2*rows-1.

Pyramid
2

Lower half (i = rows - 11)

Reuse the same two inner loops. As i shrinks, spaces grow and stars shrink — for rows = 5: 7, 5, 3, 1.

Mirror
3

Why 2 * i - 1?

Odd widths keep a single center star. Growing by two stars per step adds one on each side and preserves symmetry.

Odd counts
4

New line every row

System.out.println() after the star loop ends each diamond line in both phases.

Line break
=

Solid diamond

2 * rows - 1 lines; widest line has 2 * rows - 1 stars. O(n²) for n = rows, O(1) extra space.

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop i: spaces, stars, and which half produced the line.

HalfiSpaces rows - iStars 2*i - 1Printed row
Upper131   *
Upper223  ***
Upper315 *****
Upper407*******
Lower315 *****
Lower223  ***
Lower131   *

Total lines: 2 × 4 - 1 = 7. The widest row (i = 4) appears only in the upper half.

Use Cases

Where this diamond (and its two-phase loop structure) shows up beyond the homework prompt.

1. Combining Prior Patterns

Prove you can reuse Program 5’s row body in a second phase.

Example: extract a printRow(rows, i) helper.

2. Symmetry Practice

Odd widths and matching margins train left–right balance.

Example: swap to i stars and watch centering break.

3. Off-by-One Awareness

Starting lower at rows duplicates the peak — a classic bug.

Example: set lower start to rows and compare output.

4. Character Substitution

Swap * for digits or letters once the geometry works.

Example: print i inside the star run for a number diamond.

5. Contrast With Hollow

Solid fill vs outline (Program 9) clarifies why inner logic differs.

Example: side-by-side outputs for the same rows.

6. Complexity Intuition

2n-1 lines of Θ(n) work make O(n²) concrete.

Example: count printed characters for n = 5.

Pro Tip: in interviews, say “upper pyramid, then mirror from rows-1” before writing loops — that sequence is the whole design.

Advantages

Why this solid-diamond approach is a favorite teaching pattern.

  1. 1. Reuses Known Building Blocks

    Same space/star formulas as Program 5 — only the outer sequence changes.

  2. 2. Clear Visual Symmetry

    Odd star counts make centering errors obvious immediately.

  3. 3. Easy to Factor

    One printRow helper serves both outer loops cleanly.

  4. 4. O(1) Extra Memory

    Streaming console output needs only loop counters.

Pro Tip: master the nested-loop version first; treat printRow as a polish shortcut afterward.

Usage Tips

Small habits that keep filled-diamond code clean.

  1. 1. Extract the Row Formula

    Spaces + stars + newline belong in one place so both halves stay identical.

  2. 2. Start Lower at rows - 1

    Never start the mirror at rows unless you want a doubled middle line.

  3. 3. Keep 2 * i - 1

    Using i stars alone breaks centered diamond symmetry.

  4. 4. Prefer hasNextInt()

    Avoid FormatException when reading interactive row counts.

  5. 5. Dry-Run a Small n

    Trace rows = 3 or 4 on paper before coding larger demos.

Pro Tip: if the middle row appears twice, your lower loop almost certainly started at i = rows.

Common Pitfalls

Mistakes that commonly break filled diamond patterns.

  1. 1. Lower Half Starts at rows

    The widest line prints twice and the diamond looks “fat” in the middle.

    → Start the second outer loop at rows - 1.

  2. 2. Using i Stars Instead of 2*i - 1

    You get a left-leaning or uneven shape, not a centered diamond.

    → Keep odd star counts: 2 * i - 1.

  3. 3. Confusing With Program 9

    Hollow diamonds need different inner logic and fixed line width — not a one-line tweak.

    → Use Program 9 for outlines.

  4. 4. Wrong Space Count

    rows - i + 1 or i spaces shifts the whole figure off-center.

    → Leading spaces are exactly rows - i.

  5. 5. Blind nextInt()

    Letters or empty input throw InputMismatchException.

    → Check hasNextInt() and require rows >= 1.

Edge Cases

Check these inputs before calling the solution done.

rows = 1

Single star

Upper prints *; lower loop does not run — output is one line.

rows = 0

Empty pattern

Both halves skip — print nothing or show a validation message.

Negative

rows < 0

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

Large n

Wide middle row

Middle width is 2*n-1 stars — fine for labs; wrap or scroll on tiny terminals.

Bad input

Non-numeric ReadLine

nextInt() throws — check hasNextInt().

Half-height

rows meaning

Confirm whether the prompt means half-height or total lines (2n-1).

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Print upper half only

  • Drop the second outer loop
  • You should match Program 5

2. Hollow diamond next

  • Keep two phases; change fill to outline
  • Compare with Program 9

3. Safe input loop

  • Use hasNextInt() until rows >= 1
  • Then draw the diamond

4. Number diamond

  • Replace * with digits or i
  • Shows the geometry is independent of the fill character

Notes

  • Line count. Total lines are 2 * rows - 1; widest stars are also 2 * rows - 1.
  • Row character count before newline is (rows - i) + (2*i - 1) = rows + i - 1 — tip rows are shorter than the middle.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single star.
  • Hollow and framed variants reuse the two-phase idea but change how each row is filled.

Quick Takeaway: spaces = rows - i, stars = 2*i - 1, grow then shrink from rows - 1 — that is the filled diamond.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
printRow helper (Example 3)O(rows²)O(rows) temporary per row string

About 2 * rows - 1 lines; each line does Θ(rows) work for spaces and stars combined.

Wrap Up

🎉 Conclusion

The filled diamond is a centered pyramid plus its mirror: shared rows - i spaces and 2 * i - 1 stars, with the lower half starting at rows - 1 so the peak prints once. Master that two-phase story and hollow or framed diamonds become incremental changes.

Practice the three examples above, then continue to the diamond-in-square pattern for a framed follow-up.

Grow to rows, shrink from rows - 1, keep odd star runs — and validate half-height when reading input.

💡 Best Practices

✅ Do

  • Explain upper grow then lower shrink before coding
  • Use rows - i spaces and 2 * i - 1 stars
  • Start the lower half at rows - 1
  • Check hasNextInt() for interactive demos
  • State O(n²) time when asked about complexity

❌ Don’t

  • Start the lower loop at i == rows
  • Use i stars when you need a centered diamond
  • Confuse this solid fill with Program 9’s hollow outline
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about the filled diamond

Print the solid diamond the beginner-friendly way.

5
Core concepts
02

Spaces

rows - i

Formula
* 03

Stars

2*i - 1

Formula
1 04

Peak once

Lower from rows-1

Gotcha
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

The first outer loop runs i from 1 to rows. On each row it prints (rows - i) spaces, then (2 * i - 1) stars. That builds the upper centered pyramid. The second outer loop runs i from (rows - 1) down to 1 with the same two inner loops, mirroring the shape so the diamond closes.
The first part already prints the widest row when i equals rows. Starting the second part at rows - 1 continues with the next narrower rows without repeating the middle line.
The filled diamond prints full runs of stars using 2*i-1 stars per row. The hollow diamond uses diagonal conditions so only the outline has stars. Both use an upper phase and a lower phase starting at rows - 1.
Odd widths keep a single center star on each row and grow by one star on each side per step, which keeps left–right symmetry.
With n equal to rows, there are about 2n - 1 printed rows. Each row does Theta(n) work for spaces and stars combined, so overall time is O(n²).
Exactly 2 * rows - 1 lines. The widest line has 2 * rows - 1 stars.
Yes. Upper half is Program 5; lower half uses the same inner loops with i running like Program 6's inverted idea, but starting at rows - 1.
Check sc.hasNextInt() before sc.nextInt() and require rows >= 1 so bad input does not throw InputMismatchException.

Did you Know? 🔊

The filled diamond is Program 5’s pyramid plus its mirror: same (rows - i) spaces and (2 * i - 1) stars, with the lower half starting at rows - 1 so the widest row prints only once.

Continue to Diamond in Square

Frame a hollow diamond inside solid top and bottom rows for Program 11.

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