Java Program: Printing a Solid Square using Asterisks

Google+ Pinterest LinkedIn Tumblr +

The method for printing a solid square using “*” is I guess easier than printing an inverted triangle that I already showed you how to do. 🙂  Again here we have two classes one containing the method to print the shape and another with the main method. You can do this exercise with just one class but I’m used to making two classes having one test the other. So in my “Square” class I have a private variable “width” which is the desired width you want your square to be. I also added a constructor to set the value of “width” and finally the method “toString” to print the square. Again, I used “for” loops because it makes the solution a whole lot easier. J Here it goes:

// the class starts here!

public class Square {

    private int width;

//the constructor   

    public Square (int _width)


        width = _width;


//the method to print the square with a width of “width”

    public String toString(){

        String r = “”;

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

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

                r = r+ “*”;


            r = r + “\n”;


        return r;



So that’s that.. 😀 We then make another class to test “Square”. We will make another class “TestSquare” with the main method (using 10 as width, you can change this value if you want)

public class TestSquare {

    public static void main(String[] args) {

        Square a = new Square (10);




if you have any questions, please do leave a comment!

NOTE: This is a program that I made myself. I have tested it and came out with the desired output. I am also new in Java programming and I may not have applied the “elegant way” of writing Java programs. So please do understand. 😀


About Author

Leave A Reply