Hollow Hexagon of Stars

This program prints a hollow hexagon of stars.

Problem Statement

Write a Java program that prints a hollow hexagon of stars with 7 rows.

Source Code

1 public class HollowHexagon {
2 public static void main(String[] args) {
3 int n = 7;
4 for(int i=1; i<=n; i++) {
5 for(int j=i; j<n; j++) System.out.print(" ");
6 for(int j=1; j<=n; j++) {
7 if(i==1 || i==n || j==1 || j==n) System.out.print("* ");
8 else System.out.print(" ");
9 }
10 System.out.println();
11 }
12 }
13 }

Program Output

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

Explanation

Leading spaces shift each row to form a slanted shape, while stars are printed only at the first/last row and first/last column, creating a hollow hexagon-like polygon shape.

Quick Links to Explore