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:
-
Store the radius of the circle.
-
Provide a method to display the radius.
-
Provide a method to calculate and display the area of the circle.
-
Provide a method to calculate and display the perimeter (circumference) of the circle.
Hints / Help Points:
-
Use a variable
radiusto store the circle’s radius. -
Use
Math.PIto 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:
-
Circleclass stores the radius in a private variable. -
Constructor initializes the radius.
-
displayRadius()prints the radius. -
displayArea()calculates and prints the area usingMath.PI. -
displayPerimeter()calculates and prints the perimeter using2 × π × radius.
If you require additional resources, consider purchasing: ICSE Computer Applications Class 10 – Previous Year Question Papers & Solutions (Java Fundamentals)