w3resource

Java: Create a Circle class with area and circumference calculation

Java OOP: Exercise-4 with Solution

Write a Java program to create a class called "Circle" with a radius attribute. You can access and modify this attribute. Calculate the area and circumference of the circle.

Sample Solution:

Java Code:

//Circle.java
public class Circle {
  private double radius;

  public Circle(double radius) {
    this.radius = radius;
  }

  public double getRadius() {
    return radius;
  }

  public void setRadius(double radius) {
    this.radius = radius;
  }

  public double getArea() {
    return Math.PI * radius * radius;
  }

  public double getCircumference() {
    return 2 * Math.PI * radius;
  }
}

The above “Circle” class has a private attribute ‘radius’, a constructor that initializes this attribute with the value passed as an argument, and getter and setter methods to access and modify this attribute. It also calculates circle area and circumference using methods.

// Main.java
public class Main {
  public static void main(String[] args) {
    int r = 5;
    Circle circle = new Circle(r);
    System.out.println("Radius of the circle is " + r);
    System.out.println("The area of the circle is " + circle.getArea());
    System.out.println("The circumference of the circle is " + circle.getCircumference());
    r = 8;
    circle.setRadius(r);
    System.out.println("\nRadius of the circle is " + r);
    System.out.println("The area of the circle is now " + circle.getArea());
    System.out.println("The circumference of the circle is now " + circle.getCircumference());
  }
}

In the above main() function, we create an instance of the "Circle" class with a radius of 5, and call its methods to calculate the area and circumference. We then modify the radius using the setter method and print the updated area and circumference.

Sample Output:

Radius of the circle is 5
The area of the circle is 78.53981633974483
The circumference of the circle is 31.41592653589793

Radius of the circle is 8
The area of the circle is now 201.06192982974676
The circumference of the circle is now 50.26548245743669

Flowchart:

Flowchart: Java  OOP Exercises: Create a Circle class with area and circumference calculation.

Java Code Editor:

Improve this sample solution and post your code through Disqus.

Java OOP Previous: Calculate area and perimeter of a rectangle.
Java OOP Next: Create a Circle class and calculate its area and circumference.

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.