How to draw a square in java program example

How to draw a square in Java

In this example, We will show simple program about, How to draw a square in Java. The program has been tested and output shared in the same post.

Example Program

package com.dineshkrish;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class SquareExample {

	// method to draw square
	public static void draw(int size) {

		for (int i = 1; i <= size; i++) {

			for (int j = 1; j <= size; j++) {

				if (i == 1 || i == size || j == 1 || j == size) {

					System.out.print("* ");
				} else {

					System.out.print("  ");
				}

			}

			System.out.println();

		}

	}

	public static void main(String[] args) {

		// calling the method
		draw(10);

	}

}

Output

* * * * * * * * * * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
*                 * 
* * * * * * * * * * 
Hello everyone, I am a Founder of dineshkrish.com.