Solid and hollow rectangle star pattern in java

Java program to print solid and hollow rectangle star patterns :

 

Java program to print a particular pattern of stars or numbers is one of the commonly asked Java interview questions. Writing Java program for certain pattern helps you in mastering nested loops and recursion in java.

To print patterns of numbers and stars (*) in Java Programming, we need to use two loops, first is outer loop and the second is inner loop, where outer loop is responsible for printing rows and the inner loop is responsible for printing columns.

There are many pattern based programs, one of them is printing rectangle patterns. Rectangle patterns may be :

  • Solid
  • Hollow

 Here we will discuss both type of rectangle patterns,

Hollow-

Rectangle with having only outer area(empty from inside).

Code in Java :

//JAVA Program to print hollow rectangle star pattern

import java.util.Scanner;
public class hollowrect
{ //class declaration

public static void main(String[] args)
{ //main method declaration

Scanner sc=new Scanner(System.in); //scanner class object creation

System.out.println("Enter Number of Rows");
int r = sc.nextInt(); //taking number of rows as input

System.out.println("Enter Number of Columns");
int c = sc.nextInt(); //taking number of rows as input

if(r != c)
{ //condition for rectangle star patterns

for(int i = 1 ; i <=r ; i++)
{ //loop for rows

for(int j = 1 ; j <=c ; j++)
{ //loop for columns

if(i==1 || j==1 || i==r || j==c) //condition for hollow rectangle printing
System.out.print("*");
else
System.out.print(" ");

}//end of inner loop

System.out.println(); //for changing line

}//end of outer loop

sc.close(); //for closing scanner class(not mandatory, but good practice)

}//end of if
}//end of main method
}//end of class

Output :

Enter Number of Rows 
4
Enter Number of Columns
8
********
* *
* *
********

Solid :

Rectangle with Outer as well as inner area  filled.

Code in Java :

//JAVA Program to print solid rectangle star pattern

import java.util.Scanner;
public class solidrect
{ //class declaration

public static void main(String[] args)
{ //main method declaration

Scanner sc=new Scanner(System.in); //scanner class object creation

System.out.println("Enter Number of Rows");
int r = sc.nextInt(); //taking number of rows as input

System.out.println("Enter Number of Columns");
int c = sc.nextInt(); //taking number of rows as input

if(r != c)
{ //condition for rectangle star patterns

for(int i = 1 ; i <=r ; i++)
{ //loop for rows

for(int j = 1 ; j <=c ; j++)
{ //loop for columns
System.out.print("*");
}//end of inner loop
System.out.println(); //for changing line

}//end of outer loop

sc.close(); //for closing scanner class(not mandatory, but good practice)

}//end of if
}//end of main method
}//end of class

Output :

Enter Number of Rows
3
Enter Number of Columns
8
********
********
********