Program to Calculate the Area of a Circle in Java

Calculating the Area of a Circle

The area of a circle is calculated using the formula:

Area = π × r², where 'r' is the radius of the circle.

We will explore three different methods to calculate the area of a circle in Java programming.

Method 1: Using Basic Arithmetic

This method directly computes the area using the formula.

import java.util.Scanner;

public class CircleArea {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the radius of the circle: ");
        double radius = scanner.nextDouble();
        double area = Math.PI * radius * radius;
        System.out.printf("Area of the circle: %.2f\n", area);
        scanner.close();
    }
}
            
Input: 5.0
Output: Area of the circle: 78.54

Method 2: Using a Function

This method uses a function to calculate and return the area.

import java.util.Scanner;

public class CircleAreaFunction {
    static double calculateArea(double radius) {
        return Math.PI * radius * radius;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the radius of the circle: ");
        double radius = scanner.nextDouble();
        System.out.printf("Area of the circle: %.2f\n", calculateArea(radius));
        scanner.close();
    }
}
            
Input: 7.0
Output: Area of the circle: 153.94

Method 3: Using Recursion

This method demonstrates recursion, though recursion is not typically needed for simple mathematical operations.

import java.util.Scanner;

public class CircleAreaRecursion {
    static double recursiveArea(double radius, int times) {
        if (times == 0) {
            return Math.PI * radius * radius;
        }
        return recursiveArea(radius, times - 1);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the radius of the circle: ");
        double radius = scanner.nextDouble();
        System.out.printf("Area of the circle: %.2f\n", recursiveArea(radius, 1));
        scanner.close();
    }
}
            
Input: 4.0
Output: Area of the circle: 50.27