Java Program to calculate the perimeter of a square – In this particular piece, we will explain the various ways to calculate the perimeter of a square in Java Programming.
Suitable examples and sample programs are added for the better understanding of the given topic. The compiler has been added as well so that you can execute it yourself fairly easily.
The methods discussed in this article are as follows:
- Using Scanner Class
- Using Command Line Arguments
- Using Static Function
As we all know, a square is a two-dimensional quadrilateral figure. It is significantly used in our daily lives.
The sides of a square are all equal in nature, along with the opposite sides being parallel to each other. The angles of a square are all equal to 90 degrees.
As you can see, this is square of a side length of 25m. Thus, the perimeter of a square can be calculated as:
P = a + a + a + a = 4a.
So, the perimeter of this square is as follows:
P = 4a = 4 * 25 = 100m.
Thus, the multiple methods used to calculate the perimeter of a square 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 |
import java.util.Scanner; class PerimeterOfSquare { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the side of the square:"); double a= s.nextDouble(); double perimeter=4*a; System.out.println("perimeter of Square is: " + perimeter); } } |
1 2 |
Enter the side of the square:4 perimeter of Square is: 16.0 |
Using Command Line Arguments
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.Scanner; class PerimeterOfSquare1 { public static void main(String args[]) { double a= Double.parseDouble(args[0]); double perimeter=4*a; System.out.println("perimeter of Square is: " + perimeter); } } |
1 2 3 |
javac PerimeterOfSquare1.java java PerimeterOfSquare1 4 perimeter of Square is: 16.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 |
import java.util.Scanner; class PerimeterOfSquare { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the side of the Rhombus:"); double a= s.nextDouble(); double perimeter=PerimeterOfSquare.area(a); System.out.println("perimeter of Square is: " + perimeter); } public static double area(double l) { double a=4*l; return a; } } |
1 2 |
Enter the side of the square:4 perimeter of Square is: 16.0 |