How to Print Asterisk Triangle Pyramid in Java

Printing asterisk triangle is common programming problem given to beginners learning Java language. This will help students to grasp the power of loop programming construct. There are a number of variants of this problem. The following example shows how a triangle pyramid can be printed using Java.

       *
      ***
     *****
    *******
   *********
  ***********
 *************
***************
/**
 * How to print asterisk triangle pyramid in Java
 * @author jj
 */
public class AsteriskPyramid {
    
    public static void main(String[] args) {
        int sizeOfPyramid = 8;
        
        for(int i=1;i<=sizeOfPyramid;i++) {
			// print reduced number of spaces for each new row
            for(int j=i;j<=sizeOfPyramid-1;j++) {
                System.out.print(" ");
            }
			
			// the number of asterisks per row is 2*rownumber-1
            for(int k=1;k<=2*i-1;k++){
                System.out.print("*");
            }
            System.out.println("");
        }
    }
}