How to get the perimeter of a rectangle in Java

Overview

The perimeter of a rectangle is the total length of all its sides. These sides are the length and width (also known as breadth). The length is the longest side, and the shortest side is the width.

Syntax

2(length + width)
Syntax for perimeter

Parameters

length: This represents the length of the rectangle, which is the longest side.

width: This represents the shortest side, the width.

Return value

The value returned is a float value which is the total length of all the sides of the triangle.

Example

class HelloWorld {
public static void main( String args[] ) {
// create some lengths
float len1 = 3.4F;
float len2 = 30;
float len3 = 45;
float len4 = 100;
// create some widths
float width1 = 1.2F;
float width2 = 4;
float width3 = 9.0F;
float width4 = 0.2F;
// get the perimeters
float peri1 = 2 *(len1 * width1);
float peri2 = 2 *(len2 * width2);
float peri3 = 2 *(len3 * width3);
float peri4 = 2 *(len4 * width4);
// print the perimeters
System.out.println("The perimeter of "+len1+" and "+width1+" is = "+peri1);
System.out.println("The perimeter of "+len2+" and "+width2+" is = "+peri2);
System.out.println("The perimeter of "+len3+" and "+width3+" is = "+peri3);
System.out.println("The perimeter of "+len4+" and "+width4+" is = "+peri4);
}
}

Explanation

  • Lines 4–7: We create some lengths for the rectangles.
  • Lines 10–13: We create the widths as well.
  • Lines 16–19: We get the perimeters of the rectangles with the lengths and widths that we created.
  • Lines 22–25: We print the perimeters to the console.

Free Resources