Star pattern programs are a popular exercise in Java, often used to practice nested loops and control structures. Below, we will explore several common star patterns along with code examples and their outputs.
1. Square Star Pattern in Java
This pattern forms a square shape using stars.
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
2. Pyramid Star Pattern in Java
This pattern creates a pyramid shape.
public class PyramidStarPattern {
public static void main(String[] args) {
int n = 5; // Number of rows
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output
3. Inverted Pyramid Star Pattern in Java
This pattern forms an inverted pyramid.
public class InvertedPyramidStarPattern {
public static void main(String[] args) {
int n = 5; // Number of rows
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
System.out.print(" ");
}
for (int k = n - i; k > 0; k--) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output
4. Diamond Star Pattern in Java
This pattern creates a diamond shape.
public class DiamondStarPattern {
public static void main(String[] args) {
int n = 5; // Number of rows
// Upper half
for (int i = 0; i < n; i++) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
// Lower half
for (int i = n - 2; i >= 0; i--) {
for (int j = n - i; j > 1; j--) {
System.out.print(" ");
}
for (int k = 0; k <= i; k++) {
System.out.print("* ");
}
System.out.println();
}
}
}
Output
5. Hollow Square Star Pattern in Java
This pattern forms a hollow square.
public class HollowSquareStarPattern {
public static void main(String[] args) {
int n = 5;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 || i == n - 1 || j == 0 || j == n - 1) {
System.out.print("* ");
} else {
System.out.print(" "); // Print space for hollow part
}
}
System.out.println();
}
}
}
Output
Conclusion
These examples cover some of the most common star patterns in Java. Each pattern utilizes nested loops to control the number of rows and columns printed, demonstrating various ways to manipulate output formatting in console applications.