Java: Calculate area and perimeter of a rectangle
Write a Java program to create a class called "Rectangle" with width and height attributes. Calculate the area and perimeter of the rectangle.
Sample Solution:
Java Code:
The above class has two private attributes: 'width' and 'height', a constructor that initializes these attributes with the values passed as arguments, and getter and setter methods to access and modify these attributes. It also has two methods 'getArea()' and 'getPerimeter() ' to calculate the area and perimeter of the rectangle.
In the Main() function we create an instance of the "Rectangle" class with a width of 7 and a height of 12, and call its methods to calculate the area and perimeter. We then modify the width and height using the setter methods and print the updated rectangle area and perimeter.
Sample Output:
The area of the rectangle is 84.0 The perimeter of the rectangle is 38.0 The area of the rectangle is now 72.0 The perimeter of the rectangle is now 36.0
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to modify the "Rectangle" class to check if one rectangle can completely fit inside another.
- Write a Java program where the "Rectangle" class implements the Comparable interface to sort rectangles based on area.
- Write a Java program to add a method in the "Rectangle" class that checks if two rectangles overlap.
- Write a Java program to create an immutable "Rectangle" class where width and height cannot be changed after creation.
Go to:
Java Code Editor:
Improve this sample solution and post your code through Disqus.
PREV : Create and Modify Dog Objects.
NEXT : Create a Circle class with area and circumference calculation.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.