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

In program to find perimeter of a rectangle first user enters length and width of a rectangle using nextFloat() method of Scanner class.

java program to find perimeter of a rectangle

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

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

For example

Input:

Length = 10

Width = 5

Perimeter = 2 * (10 + 5) = 30

Here’s the java program.

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


Output:

Please enter length of rectangle: 4
Please enter width of rectangle: 5
Perimeter of rectangle: 18.0


java program to calculate area and perimeter of rectangle

To write a java program to calculate the area and perimeter of rectangle first get input from user using nextDouble() method of Scanner class.

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.println("Please enter length of rectangle: ");
      length = sc.nextDouble();
      System.out.println("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.


Also read – variables in java