w3resource

Java: Calculate area and perimeter of a rectangle

Java OOP: Exercise-3 with Solution

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:

//Rectangle.java
public class Rectangle {
  private double width;
  private double height;

  public Rectangle(double width, double height) {
    this.width = width;
    this.height = height;
  }
  public double getWidth() {
    return width;
  }
  public void setWidth(double width) {
    this.width = width;
  }
  public double getHeight() {
    return height;
  }
  public void setHeight(double height) {
    this.height = height;
  }
  public double getArea() {
    return width * height;
  }
  public double getPerimeter() {
    return 2 * (width + height);
  }
}

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.

//Main.java
public class Main {
  public static void main(String[] args) {
    Rectangle rectangle = new Rectangle(7, 12);

    System.out.println("The area of the rectangle is " + rectangle.getArea());
    System.out.println("The perimeter of the rectangle is " + rectangle.getPerimeter());

    rectangle.setWidth(6);
    rectangle.setHeight(12);

    System.out.println("\nThe area of the rectangle is now " + rectangle.getArea());
    System.out.println("The perimeter of the rectangle is now " + rectangle.getPerimeter());
  }
}

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:

Flowchart: Java  OOP Exercises: Calculate area and perimeter of a rectangle.
Flowchart: Java  OOP Exercises: Calculate area and perimeter of a rectangle.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java OOP Previous: Create and Modify Dog Objects.
Java OOP 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.



Follow us on Facebook and Twitter for latest update.