Post

Created by @nathanedwards
 at November 4th 2023, 11:32:39 pm.

AP Computer Science Exam Question

Consider the following class definition:

public class Rectangle {
    private int length;
    private int width;
    
    public Rectangle(int l, int w) {
        length = l;
        width = w;
    }
    
    public int getLength() {
        return length;
    }
    
    public int getWidth() {
        return width;
    }
    
    public int calculateArea() {
        return length * width;
    }
}

Write a program that creates two instances of the Rectangle class. The first rectangle has a length of 5 and width of 10, while the second rectangle has a length of 8 and width of 4. Calculate and print the area of each rectangle.

You may assume that the given values for length and width are valid integers.

Answer:

public class Main {
    public static void main(String[] args) {
        // Create first rectangle instance with length 5 and width 10
        Rectangle rectangle1 = new Rectangle(5, 10);
        
        // Create second rectangle instance with length 8 and width 4
        Rectangle rectangle2 = new Rectangle(8, 4);
        
        // Calculate and print the area of each rectangle
        int area1 = rectangle1.calculateArea();
        int area2 = rectangle2.calculateArea();
        
        System.out.println("Area of rectangle 1: " + area1);
        System.out.println("Area of rectangle 2: " + area2);
    }
}

Explanation:

  1. Declare a class named Main (or any other name).
  2. Define the main method which serves as the entry point of the program.
  3. Create the first rectangle instance with length 5 and width 10. Use the Rectangle constructor to initialize the rectangle1 object.
  4. Create the second rectangle instance with length 8 and width 4. Use the Rectangle constructor to initialize the rectangle2 object.
  5. Call the calculateArea method on rectangle1 to calculate the area of the first rectangle and store the result in the area1 variable.
  6. Call the calculateArea method on rectangle2 to calculate the area of the second rectangle and store the result in the area2 variable.
  7. Print the calculated area of each rectangle using the System.out.println method.