Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Basic Approach to Solve a Star Pattern in Java Using an Example
2.1.
Example: Right-Angled Triangle Star Pattern
2.2.
Java
2.2.1.
Explanation
3.
Steps to Solve
3.1.
Identify the Pattern Requirements
3.2.
Set Up the Java Environment
3.3.
Write the Code
3.4.
Implement nested loops
3.5.
Test the Pattern
3.6.
Debug & Optimize
3.7.
Document the Code
4.
Top Star Patterns in Java
4.1.
Square Star Pattern
4.2.
Java
4.3.
Inverted Pyramid Star Pattern
4.4.
Java
4.5.
Pyramid Star Pattern
4.6.
Java
4.7.
Diamond Star Pattern
4.8.
Java
4.9.
Hollow Square Star Pattern
4.10.
Java
4.11.
Square Star Pattern
4.11.1.
Example: Creating a Square Star Pattern
4.12.
Java
4.13.
Inverted Pyramid Star Pattern
4.13.1.
Example: Creating an Inverted Pyramid Star Pattern
4.14.
Java
4.15.
Pyramid Star Pattern
4.15.1.
Example: Creating a Pyramid Star Pattern
4.16.
Java
4.17.
Diamond Star Pattern
4.17.1.
Example: Creating a Diamond Star Pattern
4.18.
Java
4.19.
Hollow Square Star Pattern
4.20.
Java
5.
Frequently Asked Questions
5.1.
Why are star patterns important in learning Java?
5.2.
Can these patterns be created in other programming languages?
5.3.
How can I modify these patterns to create more complex designs?
6.
Conclusion
Last Updated: Apr 21, 2024
Easy

Star Pattern in Java

Author Rinki Deka
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Printing patterns is a common exercise for beginners learning programming. It helps develop logic and understanding of loops and conditional statements. In Java, we can print various types of patterns, including different star patterns. Star patterns are a great way to practice nested loops and learn how to control the flow of a program. 

Star Pattern in Java

In this article, we'll learn about  some basic approaches to solving star pattern problems in Java, along with example code. We'll cover several popular star patterns step-by-step, including square, pyramid, inverted pyramid, diamond, and hollow square patterns.

Basic Approach to Solve a Star Pattern in Java Using an Example

Creating a star pattern in Java involves using nested loops — one loop for the rows & another for the columns. These loops help in printing spaces & stars in the correct sequence to form the desired pattern. Let's learn the process with a simple example: a right-angled triangle star pattern.

Example: Right-Angled Triangle Star Pattern

  • Java

Java

public class StarPattern {
public static void main(String[] args) {
int rows = 5; // Number of rows you want in your pattern

for(int i = 1; i <= rows; i++) {
// Printing stars in each row
for(int j = 1; j <= i; j++) {
System.out.print("* ");
}
// Move to the next line after printing all stars in a row
System.out.println();
}
}
}

Output

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

Explanation

  • Outer Loop: This for loop runs from 1 up to the number of rows (rows). Each iteration represents a row.
     
  • Inner Loop: This for loop runs from 1 up to i (the current row number). It prints a star followed by a space for each iteration.
     
  • Print New Line: After each row's stars are printed, System.out.println(); is used to move the cursor to the next line, starting a new row of stars.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Steps to Solve

When tackling star patterns in Java, it’s crucial to approach the task methodically. Here are the general steps you can follow to construct any star pattern effectively:

Identify the Pattern Requirements

  • Determine the total number of rows needed.
     
  • Understand the sequence of spaces and stars in each row.

Set Up the Java Environment

  • Ensure Java is installed on your computer. If not, download & install the JDK from Oracle's website.
     
  • Use any text editor or an IDE like Eclipse or IntelliJ IDEA to write your code.

Write the Code

  • Start with the main method that Java requires for execution.
     
  • Declare any necessary variables, typically the number of rows.

Implement nested loops

  • The outer loop controls the number of rows.
     
  • The inner loops control the printing of spaces and stars.

Test the Pattern

  • Compile the program using javac FileName.java.
     
  • Run the program with java FileName and check the output.
     
  • Adjust the loops if the pattern does not meet the expected design.

Debug & Optimize

  • If the pattern is incorrect, check the logic in your loops.
     
  • Optimize your code to make it cleaner & more efficient.

Document the Code

  • Add comments to explain the purpose of each part of your code, especially the loops and conditionals.
     
  • This will help others understand your logic & make future modifications easier.

Top Star Patterns in Java

Java programming allows for creating a variety of star patterns. Each pattern can serve as a great exercise to understand loops and condition handling. Below are some popular star patterns that are frequently practiced by beginners:

Square Star Pattern

This pattern forms a perfect square of stars. It's straightforward as each row contains the same number of stars as there are rows.

  • Java

Java

public class SquareStarPattern {
public static void main(String[] args) {
int n = 5; // Size of the square

for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print("* ");
}
System.out.println();
}
}
}

Output

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

Inverted Pyramid Star Pattern

The inverted pyramid pattern starts wide at the top and narrows down with each row.

  • Java

Java

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

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

Output

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

Pyramid Star Pattern

This pattern resembles a pyramid with a single star at the top, increasing by two stars each row downward.

  • Java

Java

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

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

Output

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

Diamond Star Pattern

This pattern combines a pyramid and an inverted pyramid to form a diamond shape.

  • Java

Java

public class DiamondPattern {
public static void main(String[] args) {
int rows = 5; // Half of the diamond

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

// Lower half of the diamond
for (int i = rows - 1; i > 0; i--) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" ");
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*");
}
System.out.println();
}
}
}

Output

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

Hollow Square Star Pattern

Similar to the square pattern but only the border is made of stars, leaving the inside of the square empty.

  • Java

Java

public class HollowSquarePattern {
public static void main(String[] args) {
int n = 5; // Size of the square

for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
if (i == 1 || i == n || j == 1 || j == n) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}

Output

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

Square Star Pattern

The square star pattern is one of the simplest forms of star patterns you can create using Java. It involves drawing a square grid where each cell contains a star. This pattern is excellent for beginners to practice with loops.

Example: Creating a Square Star Pattern

  • Java

Java

public class SquareStar {
public static void main(String[] args) {
int size = 5; // Defines the size of the square

for (int i = 0; i < size; i++) { // Outer loop for each row
for (int j = 0; j < size; j++) { // Inner loop for each column
System.out.print("* "); // Print star followed by a space
}
System.out.println(); // Move to the next line after each row is printed
}
}
}

Output

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


Explanation:

  • Outer Loop: Runs from 0 to less than the size of the square. This loop handles the rows.
     
  • Inner Loop: Runs from 0 to less than the size, similar to the outer loop. This loop handles the columns within each row.
     
  • Print Stars: Each iteration of the inner loop prints a star followed by a space to maintain proper spacing in the row.
     
  • New Line: After each complete iteration of the inner loop (after one row is printed), System.out.println() is executed to start a new line for the next row of stars.

Inverted Pyramid Star Pattern

The inverted pyramid star pattern creates a triangle that narrows down from a wide base at the top to a point at the bottom. This pattern helps you practice decreasing loops in Java, where the number of elements in each row decreases as you move down the rows.

Example: Creating an Inverted Pyramid Star Pattern

  • Java

Java

public class InvertedPyramid {
public static void main(String[] args) {
int rows = 5; // Total number of rows for the inverted pyramid

for (int i = rows; i > 0; i--) { // Outer loop for each row
for (int j = 0; j < rows - i; j++) { // Loop for spaces before the stars
System.out.print(" "); // Print spaces
}
for (int k = 0; k < i; k++) { // Inner loop for printing stars
System.out.print("* "); // Print star followed by a space
}
System.out.println(); // Move to the next line after each row is printed
}
}
}

Output

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


Explanation:

  • Outer Loop: Runs from the number of rows to 1. Each iteration of this loop corresponds to a row of the pyramid.
     
  • First Inner Loop for Spaces: Before starting to print stars, this loop adds spaces. The number of spaces increases as you move to lower rows, aligning the stars to the right.
     
  • Second Inner Loop for Stars: Prints the stars. The number of stars decreases with each row, creating the inverted pyramid effect.
     
  • New Line: System.out.println() is used at the end of each row's loops to start a new line, ensuring the pattern forms correctly.
     

This pattern not only enhances understanding of nested loops but also involves adjusting the inner loop counters differently for spaces and stars, showcasing how loop controls can create complex designs.

Pyramid Star Pattern

The pyramid star pattern forms a symmetrical triangle with a single star at the top and progressively wider rows of stars as you move downwards. This pattern teaches you how to manage spaces and star counts in tandem to create a visually appealing symmetric shape.

Example: Creating a Pyramid Star Pattern

  • Java

Java

public class PyramidStar {
public static void main(String[] args) {
int rows = 5; // The total number of rows in the pyramid

for (int i = 1; i <= rows; i++) { // Outer loop for each row
for (int j = rows - i; j > 0; j--) { // Inner loop for spaces
System.out.print(" "); // Print spaces to align stars in pyramid shape
}
for (int k = 1; k < 2 * i; k++) { // Inner loop for stars
System.out.print("*"); // Print stars to form the pyramid
}
System.out.println(); // Move to the next line after each row is printed
}
}
}

Output

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


Explanation

  • Outer Loop: Controls the number of rows. It starts at 1 and increments until it reaches the total rows specified.
     
  • First Inner Loop for Spaces: This loop decreases the number of spaces as the row number increases, aligning the stars centrally.
     
  • Second Inner Loop for Stars: This loop increases the number of stars as you move down each row, creating the pyramid shape. It prints twice the row number minus one star to maintain symmetry.
     
  • New Line: After each row's pattern of stars and spaces is completed, System.out.println() ensures the next row starts on a new line.
     

This pattern is excellent for mastering loop control structures and understanding how to manipulate output for desired visual arrangements.

Diamond Star Pattern

The diamond star pattern is an extension of the pyramid pattern, consisting of both an upward and downward facing pyramid to form a diamond shape. This pattern is a bit more complex because it involves mirroring the top half with the bottom, requiring careful control of spaces and star counts.

Example: Creating a Diamond Star Pattern

  • Java

Java

public class DiamondStar {
public static void main(String[] args) {
int rows = 5; // Number of rows for each half of the diamond

// Upper half of the diamond (including the middle row)
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" "); // Print spaces before stars in each row
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*"); // Print stars to form the upper part of the diamond
}
System.out.println(); // Move to the next line
}

// Lower half of the diamond
for (int i = rows - 1; i > 0; i--) {
for (int j = 1; j <= rows - i; j++) {
System.out.print(" "); // Print spaces before stars in each row
}
for (int j = 1; j <= 2 * i - 1; j++) {
System.out.print("*"); // Print stars to form the lower part of the diamond
}
System.out.println(); // Move to the next line
}
}
}

Output

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


Explanation:

  • Outer Loop for Upper Half: Starts from 1 and goes up to the number of rows, increasing the number of stars in each row to create the upper half of the diamond.
     
  • Inner Loop for Spaces (Upper Half): Decreases the number of spaces as the rows increase to keep the stars centered.
     
  • Inner Loop for Stars (Upper Half): Increases the number of stars to form the correct width for each row.
     
  • Outer Loop for Lower Half: Mirrors the upper half but in reverse, reducing the number of stars to taper down the diamond shape.
     
  • Inner Loop for Spaces (Lower Half): Adjusts the spaces to align the stars correctly as the diamond narrows.
     
  • Inner Loop for Stars (Lower Half): Decreases the number of stars to complete the lower half of the diamond.
     

This pattern not only helps in practicing nested loops but also in understanding how to effectively mirror patterns to create visually appealing designs.

Hollow Square Star Pattern

The hollow square star pattern creates a square made of stars, with an empty or hollow center. This pattern emphasizes the use of conditionals within loops to differentiate between when to print stars and when to leave spaces.

Example: Creating a Hollow Square Star Pattern

  • Java

Java

public class HollowSquare {
public static void main(String[] args) {
int size = 5; // Dimensions of the square

for (int i = 1; i <= size; i++) { // Loop for each row
for (int j = 1; j <= size; j++) { // Loop for each column
// Print stars for the border of the square
if (i == 1 || i == size || j == 1 || j == size) {
System.out.print("* ");
} else {
System.out.print(" "); // Print spaces inside the square
}
}
System.out.println(); // Move to the next line after completing a row
}
}
}

Output

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


Explanation:

  • Outer Loop: Runs through each row from 1 to the specified size.
     
  • Inner Loop: Runs through each column in each row.

Conditional Statements:

  • Checks if the current row (i) or column (j) is the first or last. If true, it prints a star (* ), creating the border of the square.
     
  • If the condition is false (meaning the loop is handling an internal row or column), it prints a space ( ) to create the hollow effect inside the square.
     

This pattern is particularly useful for learning how to manipulate output within a fixed structure while integrating conditionals to modify the pattern based on the position within the loop structure.

Frequently Asked Questions

Why are star patterns important in learning Java?

Star patterns help understand the use of loops and conditionals, key concepts in programming that are essential for controlling flow and generating dynamic outputs.

Can these patterns be created in other programming languages?

Yes, the logic behind star patterns is universal and can be applied in any programming language that supports loop and conditional constructs, such as Python, C++, or JavaScript.

How can I modify these patterns to create more complex designs?

Experiment with the loops and conditionals. Adjust the number of rows, the logic for spaces, and the inclusion of different characters to expand beyond simple stars, creating more intricate and customized patterns.

Conclusion

In this article, we have learned how to create basic and complex star patterns in Java. We started with simple square and pyramid shapes, moved to more complex diamond and inverted pyramid patterns, and also discussed a hollow square pattern. Each pattern demonstrated the use of nested loops and conditionals, reinforcing Java's capabilities for handling such structures effectively. These exercises are not only crucial for beginners to master fundamental programming concepts but also serve as a creative way to visualize code execution and flow control.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Difference Between Byte Code and Machine Code
Next article
Why is Java Platform Independent?
Live masterclass