The following program to create Simple Hour Glass in Java.

### HourGlass.java

```package com.javatraineronline;
public class HourGlass {
public static void main(String[] args) {
// Initialize the 2D array. Here we've used 6*6 matrix
int[][] array = {{-1,-1,0,-9,-2,-2},{-2, -1, -6, -8, -2, -5},{-1, -1, -1, -2, -3, -4},{-1, -9, -2, -4, -4, -5},{-7, -3, -3, -2, -9, -9},{-1, -3, -1, -2, -4, -5}};
//Loop through the possible combination of hour glass with the rows and columns of the matrix
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
System.out.print(array[i][j] + " " + array[i][j+1] + " " + array[i][j+2]);// Make the hour glass with specified row and column(1st row of the hour glass)
System.out.println();
System.out.print("   "+array[i+1][j+1]);//(2nd row of the hour glass)
System.out.println();
System.out.print(array[i+2][j] + " " + array[i+2][j+1] + " " + array[i+2][j+2]);//(3rd row of the hour glass)
System.out.println();
System.out.println();
}
// Make space if needed
System.out.println();
System.out.println();
}
}
}
```

### Output

[su_box title=”Output for HourGlass.java”]
-1 -1 0
-1
-1 -1 -1

-1 0 -9
-6
-1 -1 -2

0 -9 -2
-8
-1 -2 -3

-9 -2 -2
-2
-2 -3 -4

-2 -1 -6
-1
-1 -9 -2

-1 -6 -8
-1
-9 -2 -4

-6 -8 -2
-2
-2 -4 -4

-8 -2 -5
-3
-4 -4 -5

-1 -1 -1
-9
-7 -3 -3

-1 -1 -2
-2
-3 -3 -2
[/su_box]

Categories:

Tags: