Java program to find the perimeter of a rectangle – In this distinct article, we will discuss the multiple methods used to calculate the perimeter of a rectangle in Java programming.
Suitable examples and sample outputs are included in this piece as well for better interpretation. The compiler has also been added so that you can execute it yourself pretty easily.
The ways to find out the perimeter of a rectangle as per the blog are as follows:
- Using Scanner Class
- Using Command Line Arguments
- Using Static Function
As we all know, a rectangle is a two-dimensional quadrilateral figure in the field of geometry. The opposite sides of a rectangle are equal and parallel in nature.
All of the angles in a rectangle are 90 degrees.
As you can see, this is a rectangle with a length of 28 units and a breadth of 17 units.
Thus, the perimeter of a rectangle can be calculated using this formula:
P = 2(l + b)
So, the perimeter of the given rectangle is as follows:
P = 2(28 + 17) = 90 units.
Hence, the methods used to calculate the perimeter of a rectangle in Java programming are as follows:
Using Scanner Class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.util.Scanner; class PerimeterOfRectangle { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the length of the Rectangle:"); double l= s.nextDouble(); System.out.println("Enter the width of the Rectangle:"); double b= s.nextDouble(); double perimeter=2*(l+b); System.out.println("perimeter of Rectangle is: " + perimeter); } } |
1 2 3 |
Enter the length of the Rectangle:3 Enter the width of the Rectangle:4 perimeter of Rectangle is: 14.0 |
Using Command Line Arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import java.util.Scanner; class PerimeterOfRectangle1 { public static void main(String args[]) { double l= Double.parseDouble(args[0]); double b= Double.parseDouble(args[1]); double perimeter=2*(l+b); System.out.println("perimeter of Rectangle is: " + perimeter); } } |
1 2 3 |
javac PerimeterOfRectangle1.java java PerimeterOfRectangle1 3 4 perimeter of Rectangle is: 14.0 |
Using Static Function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.Scanner; class PerimeterOfRectangle { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the length of the Rectangle:"); double l= s.nextDouble(); System.out.println("Enter the width of the Rectangle:"); double b= s.nextDouble(); double perimeter=PerimeterOfRectangle.area(l,b); System.out.println("perimeter of Rectangle is: " + perimeter); } public static double area(double l,double b) { double a=2*(l+b); return a; } } |
1 2 3 |
Enter the length of the Rectangle:3 Enter the width of the Rectangle:4 perimeter of Rectangle is: 14.0 |