Java program to find perimeter of a rectangle

Let’s learn java program to find perimeter of a rectangle.

Java program to find perimeter of a rectangle

java program to find perimeter of a rectangle

In program to find perimeter of a rectangle first user enters length and width of a rectangle.

This user input is stored in variable length and width of datatype integer. Then using below formula find perimeter of rectangle,

perimeter = 2 * (length + width). Lastly print the perimeter value.

Also read – java program to find the area of rectangle using class and object

For example,

Input:

Length = 10

Width = 5

Perimeter = 2 * (10 + 5) = 30

Here’s program to find the perimeter of the rectangle,

import java.util.Scanner;

public class PerimeterOfRectangleDemo
{    
   public static void main(String []args)
   {
      int length, width, perimeter;
      Scanner sc = new Scanner(System.in);
      System.out.print("Enter length of rectangle : ");
      length = sc.nextFloat();
      System.out.print("Enter width of rectangle : ");
      width  = sc.nextFloat();
      perimeter = 2 * (length + width);
      System.out.println("Perimeter of rectangle : " + perimeter);
      sc.close();
   }          
}



Output:

Enter length of rectangle : 2
Enter width of rectangle : 5
Perimeter of rectangle : 14

Write a program to calculate the area and perimeter of rectangle

To write a java program to calculate the area and perimeter of a rectangle first get input from user using scanner object.

Here user enters length and width of rectangle and it is stored in variables length and width of datatype double.

Then use below formula to find perimeter and area of rectangle,

perimeter = 2 * (length + width)

area = length * width

Lastly print area and perimeter on the console,

import java.util.Scanner;

public class CalculateAreaAndPerimeter 
{
   public static void main(String[] args) 
   {
      double length, width, area, perimeter;
      // creating scanner class object
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter length of rectangle: ");
      length = sc.nextDouble();
      System.out.print("Please enter width of rectangle: ");
      width  = sc.nextDouble();
      // perimeter  of rectangle
      perimeter = 2 * (length + width);
      // area of rectangle 
      area = length * width;
      System.out.println("Perimeter of rectangle is: " + perimeter + " units.");
      System.out.println("Area of rectangle is: " + area + " sq. units.");
      sc.close();
   }
}


Output:

Please enter length of rectangle: 50
Please enter width of rectangle: 20
Perimeter of rectangle is: 140.0 units.
Area of rectangle is: 1000.0 sq. units.