Open In App

Java Program to Find out the Area and Perimeter of Rectangle using Class Concept

The perimeter is the length of the outline of a shape. To find the perimeter of a rectangle or square you have to add the lengths of all four sides. x is in this case the length of the rectangle while y is the width of the rectangle. The area is the measurement of the surface of a shape.

The main task here is to create a class that can be used to find the Area and Perimeter of a rectangle. 



By using the formula for Area of Rectangle and Perimeter of Rectangle:

Area of Rectangle = Length * Breadth
Perimeter of Rectangle = 2 * (Length + Breadth)

Example:



Length = 10

Breadth = 20

Area of rectangle is = 200

Perimeter of rectangle is = 60

Approach :

Example:




// Java program to create a class to
// print the area and perimeter of a
// rectangle
 
import java.util.*;
 
// Rectangle Class File
public class Rectangle {
 
    // Variable of data type double
    double length;
    double width;
 
    // Area Method to calculate the area of Rectangle
    void Area()
    {
        double area;
        area = this.length * this.width;
        System.out.println("Area of rectangle is : "
                           + area);
    }
 
    // Perimeter Method to calculate the Perimeter of
    // Rectangle
    void Perimeter()
    {
        double perimeter;
        perimeter = 2 * (this.length + this.width);
        System.out.println("Perimeter of rectangle is : "
                           + perimeter);
    }
}
 
 class Use_Rectangle {
    
    public static void main(String args[])
    {
        // Object of Rectangle class is created
        Rectangle rect = new Rectangle();
 
        // Assigning the value in the length variable of
        // Rectangle Class
        rect.length = 15.854;
 
        // Assigning the value in the width variable of
        // Rectangle Class
        rect.width = 22.65;
 
        System.out.println("Length = " + rect.length);
        System.out.println("Width = " + rect.width);
 
        // Calling of Area method of Rectangle Class
        rect.Area();
 
        // Calling of Perimeter method of Rectangle Class
        rect.Perimeter();
    }
}

Output
Length = 15.854
Width = 22.65
Area of rectangle is : 359.09309999999994
Perimeter of rectangle is : 77.008

Time complexity: O(1) since performing constant operations

Auxiliary Space: O(1)


Article Tags :