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 :
- First, we will create a class called Rectangle in which we will define the variable length and breadth. And the method Area and Perimeter to calculate the Area and Perimeter of Rectangle.
- Then we will create another class in which we will create a main method.
- Inside the main method, the object of the rectangle is created using which we can call assign the values to the variable of Rectangle class, and after assigning the values the methods of the Rectangle class will be called to calculate the Area and Perimeter of Rectangle.
- Both the methods of the Rectangle class will use the values of length and breadth that we had passed from the main method using the object of that class. And the result will get printed.
Example:
Java
import java.util.*;
public class Rectangle {
double length;
double width;
void Area()
{
double area;
area = this .length * this .width;
System.out.println( "Area of rectangle is : "
+ area);
}
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[])
{
Rectangle rect = new Rectangle();
rect.length = 15.854 ;
rect.width = 22.65 ;
System.out.println( "Length = " + rect.length);
System.out.println( "Width = " + rect.width);
rect.Area();
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)
Last Updated :
23 Jul, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...