Table of contents
1.
Introduction
2.
What Is a Diamond Pattern in Java?
3.
Why Learn Pattern Programs in Java?
3.1.
1. Enhances Understanding of Loops and Nested Structures
3.2.
2. Improves Logical Thinking and Problem-Solving
3.3.
3. Helps in Coding Interviews and Assessments
4.
Logic Behind the Diamond Pattern
5.
Problem Description
6.
Illustration
7.
Algorithm
8.
Using do-while Loop:
9.
Using while Loop
10.
Using for Loop:
11.
Time & Space complexity
11.1.
Time Complexity
11.2.
Space Complexity
12.
Real-World Use Cases of Pattern Programs
12.1.
1. Why Practice Pattern Problems in Java Interviews
12.2.
2. Logical Thinking and Loop Mastery
13.
Frequently Asked Questions
13.1.
Can I use any character other than asterisks () to create the diamond pattern? 
13.2.
How can I modify the code to print a hollow diamond pattern? 
13.3.
Can I create a diamond pattern with an even number of lines? 
14.
Conclusion
Last Updated: Jul 6, 2025
Easy

Diamond Pattern in Java

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Patterns are a fundamental concept in every programming language that allows us to create visually appealing & structured outputs. Every programmer must have solved this concept at least once in his lifetime. In Java, one popular pattern is the diamond pattern, which creates a diamond shape using characters or symbols. Patterns are a great way for beginners to practice loops, conditionals & printing techniques. 

In this article, we'll explain the diamond pattern in detail, which covers the problem description, illustration, algorithm & code examples with different looping methods. 

What Is a Diamond Pattern in Java?

A diamond pattern in Java is a symmetrical shape formed using characters (usually asterisks *) printed to the console. It visually resembles a diamond or rhombus with a top point, middle widest line, and a tapering bottom. The pattern is printed using nested loops to manage spaces and stars on each line, ensuring symmetry on both sides. A typical diamond has an odd number of rows to maintain this symmetry.

Example (5-row diamond):

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

The top half increases stars and decreases spaces, while the bottom half does the reverse. Understanding loop placement and spacing logic is key to implementing this in Java.

Why Learn Pattern Programs in Java?

1. Enhances Understanding of Loops and Nested Structures

Pattern programs offer a hands-on way to practice loop logic, especially nested for or while loops. They help reinforce how outer loops manage rows and inner loops handle spaces or characters. Writing these programs improves your confidence in flow control, iteration count, and condition-based execution. As you debug misaligned patterns, you naturally deepen your understanding of loop behavior.

2. Improves Logical Thinking and Problem-Solving

Creating visually correct patterns develops algorithmic thinking. You learn how to break complex shapes into smaller, logical components and build them using conditions and arithmetic. This mindset is transferable to solving real-world problems—like data transformations, layout rendering, and graphical structure generation in UI or game development.

3. Helps in Coding Interviews and Assessments

Many coding interviews—especially for beginners—feature pattern questions to test your grasp of loops and logic under pressure. They’re common in entrance tests, online assessments, and campus placements. Being comfortable with patterns shows you can write precise, structured code and manage edge cases, making you a stronger candidate.

Logic Behind the Diamond Pattern

  • Identifying Rows and Columns

The diamond pattern consists of two symmetrical parts: the top (increasing stars) and the bottom (decreasing stars). For a diamond with n rows (odd number like 5 or 7), the pattern has a middle line with the most stars. Rows above the middle increase in width, and those below decrease.

For a 5-row diamond:

RowSpacesStars
121
213
305
413
521

Each row contains:

Spaces = n/2 - current_row_index (for top half)

Stars = 2 * current_row_index + 1

Understanding this structure helps you divide the pattern into top and bottom halves for looping logic.

  • Using Spaces and Stars Effectively

To form a perfect diamond shape, both spaces and stars must be carefully aligned. Spaces push the stars to the center, while stars create the visual content.

Java implementation typically uses three nested loops:

  • Outer loop: controls rows
  • First inner loop: prints spaces (System.out.print(" "))
  • Second inner loop: prints stars (System.out.print("*"))

Pseudo-code snippet:

for (int i = 0; i < n; i++) {
    // Calculate spaces and stars for current row
    int spaces = Math.abs(n/2 - i);
    int stars = n - 2 * spaces;

    // Print spaces
    for (int j = 0; j < spaces; j++) {
        System.out.print(" ");
    }

    // Print stars
    for (int j = 0; j < stars; j++) {
        System.out.print("*");
    }

    System.out.println(); // Move to next line
}

This structure ensures consistent alignment and can be easily adapted to different character patterns or sizes.

Problem Description

The problem at hand is to create a diamond pattern in Java. The diamond pattern consists of a series of lines, where each line contains a specific number of characters or symbols. The pattern starts with a single character at the top and gradually increases in width until the middle line, forming the upper half of the diamond. Then, the width decreases symmetrically, forming the lower half of the diamond until it reaches a single character at the bottom.

The key characteristics of the diamond pattern are:

1. The pattern is symmetric both horizontally & vertically.
 

2. The number of lines in the pattern is always odd.
 

3. The middle line of the pattern has the maximum width.
 

4. The width of the lines increases by 2 characters on each side until the middle line & then decreases by 2 characters on each side.
 

5. The characters used to create the diamond can be asterisks (*), plus signs (+), or any other symbol specified by the user.


The challenge is to write a Java program that takes an integer input n from the user, representing the number of lines in the diamond pattern, & then prints the corresponding diamond pattern using the specified character.

Illustration

To better understand the diamond pattern, let's look at an example. 

Consider the following illustration of a diamond pattern with 5 lines:

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


In this illustration, we can observe the following:

1. The pattern consists of 5 lines.
 

2. The middle line (line 3) has a maximum width of 5 characters.
 

3. The width of the lines increases by 2 characters on each side from the top to the middle line.
 

4. The width of the lines decreases by 2 characters on each side from the middle line to the bottom.
 

5. The pattern is symmetric both horizontally & vertically.
 

Now, let's consider another example with 7 lines:

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


This illustration follows the same principles as the previous one, but with 7 lines instead of 5.

Algorithm

To create a diamond pattern in Java, we can follow this step-by-step algorithm:

1. Take an integer input n from the user, representing the number of lines in the diamond pattern.
 

2. Initialize a loop variable i to 1, representing the current line number.
 

3. Start an outer loop that iterates from 1 to n:
 

   a. Calculate the number of spaces required before the characters on the current line using the formula: spaces = Math.abs(n/2 - i + 1).
 

   b. Print the required number of spaces using another loop.
 

   c. Calculate the number of characters to be printed on the current line using the formula: characters = n - 2 * spaces.
 

   d. Print the required number of characters using another loop.
 

   e. Move to the next line.
 

   f. Increment the loop variable i.
 

4. End the outer loop.
 

The algorithm can be concluded in pseudocode as mentioned below:

function printDiamondPattern(n):
    for i = 1 to n:
        spaces = Math.abs(n/2 - i + 1)
        print spaces
        characters = n - 2 * spaces
        print characters
        move to next line


This algorithm provides a general approach to creating the diamond pattern. It can be implemented with different looping methods in Java, like do-while loops, while loops & for loops.

Let’s look at the code using all the three methods :

Using do-while Loop:

import java.util.Scanner;

public class DiamondPatternDoWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of lines: ");
        int n = scanner.nextInt();
        scanner.close();

        int i = 1;
        int spaces, characters;

        // Upper half of the diamond
        do {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            do {
                System.out.print(" ");
                j++;
            } while (j <= spaces);

            // Print characters
            int k = 1;
            do {
                System.out.print("*");
                k++;
            } while (k <= characters);


            System.out.println();
            i++;
        } while (i <= (n+1)/2);


        // Lower half of the diamond
        i = (n-1)/2;
        do {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            do {
                System.out.print(" ");
                j++;
            } while (j <= spaces);


            // Print characters
            int k = 1;
            do {
                System.out.print("*");
                k++;
            } while (k <= characters);


            System.out.println();
            i--;
        } while (i >= 1);
    }
}
You can also try this code with Online Java Compiler
Run Code

Output

Enter the number of lines: 3
*
***
*

Using while Loop

import java.util.Scanner;

public class DiamondPatternWhile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of lines: ");
        int n = scanner.nextInt();
        scanner.close();

        int i = 1;
        int spaces, characters;

        // Upper half of the diamond
        while (i <= (n+1)/2) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            while (j <= spaces) {
                System.out.print(" ");
                j++;
            }

            // Print characters
            int k = 1;
            while (k <= characters) {
                System.out.print("*");
                k++;
            }


            System.out.println();
            i++;
        }

        // Lower half of the diamond
        i = (n-1)/2;
        while (i >= 1) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            int j = 1;
            while (j <= spaces) {
                System.out.print(" ");
                j++;
            }

           // Print characters
            int k = 1;
            while (k <= characters) {
                System.out.print("*");
                k++;
            }


            System.out.println();
            i--;
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Enter the number of lines: 3
*
***
*

Using for Loop:

import java.util.Scanner;

public class DiamondPatternFor {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of lines: ");
        int n = scanner.nextInt();
        scanner.close();

        int spaces, characters;

        // Upper half of the diamond
        for (int i = 1; i <= (n+1)/2; i++) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }


            // Print characters
            for (int k = 1; k <= characters; k++) {
                System.out.print("*");
            }


            System.out.println();
        }

        // Lower half of the diamond
        for (int i = (n-1)/2; i >= 1; i--) {
            spaces = Math.abs(n/2 - i + 1);
            characters = n - 2 * spaces;


            // Print spaces
            for (int j = 1; j <= spaces; j++) {
                System.out.print(" ");
            }


            // Print characters
            for (int k = 1; k <= characters; k++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
You can also try this code with Online Java Compiler
Run Code


Output

Enter the number of lines: 3
*
***
*


These code examples show how to create a diamond pattern in Java with different looping methods: do-while loops, while loops & for loops. Each example takes an integer input n from the user, representing the number of lines in the diamond pattern, & then prints the corresponding diamond pattern using asterisks (*).

The code is structured into two parts: the upper half of the diamond & the lower half of the diamond. The upper half is printed by iterating from 1 to (n+1)/2, while the lower half is printed by iterating from (n-1)/2 to 1.

In each iteration, the number of spaces & characters to be printed on the current line is calculated based on the line number & the total number of lines. The spaces are printed first, followed by the characters.

Time & Space complexity

Now, let's analyze the time & space complexity of the diamond pattern algorithm.

Time Complexity

The time complexity of the diamond pattern algorithm depends on the number of lines in the pattern, which is denoted by n.

In the given code examples, the outer loop iterates (n+1)/2 times for the upper half of the diamond & (n-1)/2 times for the lower half of the diamond. In each iteration, there are two inner loops: one for printing spaces & another for printing characters.

The number of spaces printed in each line varies from 0 to n/2, & the number of characters printed varies from 1 to n. Therefore, the total number of iterations in the inner loops is proportional to n.

Considering the outer loop & the inner loops, the overall time complexity of the algorithm is O(n^2), where n is the number of lines in the diamond pattern.

Space Complexity

The space complexity of the diamond pattern algorithm is O(1) because it uses only a constant amount of extra space to store variables like i, spaces & characters. The space required does not depend on the input size n.

The algorithm does not use any data structures that grow with the input size, & the output is printed directly to the console without storing it in memory.

Therefore, the diamond pattern algorithm has a space complexity of O(1), which means it uses a constant amount of extra space regardless of the input size.

In summary, the diamond pattern algorithm has a time complexity of O(n^2) & a space complexity of O(1), where n is the number of lines in the diamond pattern.

Real-World Use Cases of Pattern Programs

1. Why Practice Pattern Problems in Java Interviews

Pattern-based questions are commonly asked in Java interviews, especially for freshers and entry-level positions. These questions test how well a candidate understands loops, conditional logic, and attention to detail. Interviewers don’t just look for the correct output—they assess how candidates approach problem decomposition, plan loop structures, and manage iterations. It helps them evaluate coding habits, logical thinking, and syntax accuracy in a low-complexity but high-insight environment.

Example Interview Prompt:
"Write a program to print a hollow diamond pattern of stars for a given number of rows."

Such problems appear simple but demand loop control, condition handling, and spacing logic—which are fundamental skills in programming. Excelling at these questions demonstrates a strong grasp of Java basics and problem-solving under time constraints.

2. Logical Thinking and Loop Mastery

Practicing pattern problems regularly builds logical reasoning and improves command over looping structures—two core competencies for any Java developer. Many patterns require the developer to think in terms of rows, columns, and conditions, forcing them to divide the problem into manageable parts (e.g., upper half and lower half of a diamond). This teaches modular thinking, a valuable skill in solving real-world coding challenges.

Additionally, understanding how loop variables interact (like in nested loops) builds intuition for writing precise, optimized code. These exercises also reveal common pitfalls—like off-by-one errors or improper conditions—which programmers must learn to avoid. Mastering loops through patterns forms a solid foundation for tackling algorithms, data structures, and even UI logic, where shape or alignment might matter.

Frequently Asked Questions

Can I use any character other than asterisks () to create the diamond pattern? 

Yes, you can replace the asterisks () in the code with any character of your choice to create the diamond pattern.

How can I modify the code to print a hollow diamond pattern? 

To print a hollow diamond pattern, you need to modify the inner loop that prints characters. Print asterisks (*) only for the first & last characters in each line, & print spaces in between.

Can I create a diamond pattern with an even number of lines? 

No, the diamond pattern algorithm assumes an odd number of lines. If you provide an even number, the pattern will be slightly asymmetric.

Conclusion

In this article, we discussed the diamond pattern in Java. We started the article by understanding the problem description & visualizing the pattern through illustrations. We then discussed the step-by-step algorithm to create the diamond pattern. We provided code examples using different looping methods in Java, like do-while loops, while loops & for loops. 

Live masterclass