How to calculate the area, diameter, and circumference of a circle in Java

2 Answers

0 votes
class Main {
    public static void main(String[] args) {
        int radius = 3;
        float PI = 3.14f;

        float area = PI * radius * radius;
        System.out.format("Area = %.2f\n", area);

        float diameter = 2 * radius;
        System.out.format("Diameter = %.2f\n", diameter);

        float circumference = 2 * PI * radius;
        System.out.format("Circumference = %.2f\n", circumference);
    }
}
    
    
/*
run:
 
Area = 28.26
Diameter = 6.00
Circumference = 18.84
     
*/

 



answered Feb 18, 2016 by avibootz
edited 4 hours ago by avibootz
0 votes
public class CircleCalculator {

    /**
     * Record to hold all calculated circle metrics cleanly (Java 14+).
     */
    public record CircleMetrics(double diameter, double circumference, double area) {}

    /**
     * Calculates the diameter, circumference, and area of a circle.
     * 
     * @param radius The radius of the circle (must be non-negative).
     * @return CircleMetrics containing the diameter, circumference, and area.
     * @throws IllegalArgumentException if the radius is negative.
     */
    public static CircleMetrics calculateMetrics(double radius) {
        // Guard clause: radius cannot be negative
        if (radius < 0.0) {
            throw new IllegalArgumentException("Radius cannot be negative.");
        }

        double diameter = 2.0 * radius;
        double circumference = 2.0 * Math.PI * radius;
        
        // Standard multiplication (radius * radius) is more efficient than Math.pow(radius, 2)
        double area = Math.PI * (radius * radius);

        return new CircleMetrics(diameter, circumference, area);
    }

    public static void main(String[] args) {
        try {
            double radius = 3.0;
            
            // Retrieve calculated metrics
            CircleMetrics metrics = calculateMetrics(radius);

            // Output results formatted to 2 decimal places using printf
            System.out.printf("Radius: %.2f%n", radius);
            System.out.printf("Diameter: %.2f%n", metrics.diameter());
            System.out.printf("Circumference: %.2f%n", metrics.circumference());
            System.out.printf("Area: %.2f%n", metrics.area());
        } 
        catch (IllegalArgumentException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
} 


/*
run:
 
Radius: 3.00
Diameter: 6.00
Circumference: 18.85
Area: 28.27
     
*/

 



answered 4 hours ago by avibootz

Related questions

...