Table of Contents

    Java Program to Implement a Circle Class

    Question: Java Program to Implement a Circle Class

    Task:
    Write a Java class to represent a circle. Your class should:

    1. Store the radius of the circle.

    2. Provide a method to display the radius.

    3. Provide a method to calculate and display the area of the circle.

    4. Provide a method to calculate and display the perimeter (circumference) of the circle.

    Hints / Help Points:

    • Use a variable radius to store the circle’s radius.

    • Use Math.PI to calculate the area and perimeter.

    • Area = π × radius × radius

    • Perimeter = 2 × π × radius

    Example Usage:

    
    Circle c = new Circle(5);
    c.displayRadius();    // Output: Radius: 5
    c.displayArea();      // Output: Area: 78.54
    c.displayPerimeter(); // Output: Perimeter: 31.42
    
    

    Solution:

    
    // Circle class
    class Circle {
        private double radius;
    
        // Constructor
        public Circle(double radius) {
            this.radius = radius;
        }
    
        // Method to display radius
        public void displayRadius() {
            System.out.println("Radius: " + radius);
        }
    
        // Method to display area
        public void displayArea() {
            double area = Math.PI * radius * radius;
            System.out.println("Area: " + area);
        }
    
        // Method to display perimeter
        public void displayPerimeter() {
            double perimeter = 2 * Math.PI * radius;
            System.out.println("Perimeter: " + perimeter);
        }
    }
    
    // Test class
    public class TestCircle {
        public static void main(String[] args) {
            Circle c1 = new Circle(5);
    
            c1.displayRadius();    // Radius: 5
            c1.displayArea();      // Area: 78.53981633974483
            c1.displayPerimeter(); // Perimeter: 31.41592653589793
        }
    }
    
    

    Explanation:

    1. Circle class stores the radius in a private variable.

    2. Constructor initializes the radius.

    3. displayRadius() prints the radius.

    4. displayArea() calculates and prints the area using Math.PI.

    5. displayPerimeter() calculates and prints the perimeter using 2 × π × radius.