Java Program: Printing a Hollow Square using Asterisks

Google+ Pinterest LinkedIn Tumblr +

This took me some time before I got the solution. Printing a solid square is easy, but a hollow one is a little bit tricky. For this exercise I used an “if-else” statement so I can create the hollow space in the square. So this is class “HollowSquare”. I still have the private variable “width” for the desired width of the hollow square, and also a constructor to set the “width” variable. And of course the “toString” method to create and print the hollow square. 

// class starts here!

 public class HollowSquare {

    private int width;

 //the constructor for “HollowSquare”

     public HollowSquare (int _width){

        width = _width;

    }

 // the toString method to create and print the hollow square

     public String toString(){

        String r = “”;

        for(int i=0; i

            for(int j=0; j

                if(i==0 || j==0 || i==(width-1))

                    r = r + “*”;

                else if (j==(width-1))

                    r = r + “*”;

                else

                    r = r + ” “;

            }

            r = r + “\n”;

        }

        return r;

    }

}

So there, the hard part’s done! 😀 So we then make another class “TestHollowSquare” with the main method (using 10 as width, you can change this value if you want to) to test the class “HollowSquare”.

public class TestHollowSquare {

    public static void main (String[] args){

        HollowSquare b = new HollowSquare (10);

        System.out.print(b.toString());

    }

}

Tracing the “toString” method will help you understand how the hollow square was created. But if you have any questions please do leave a message or 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. 😀

Share.

About Author

Leave A Reply