Java Code Example: Volume and Surface Area of a Sphere

A ball (sphere) is a three-dimensional shape with a perfectly round surface. The volume and surface area of a sphere are important mathematical properties used in physics, engineering, and computer graphics.

Formulas:

Volume of a Sphere:

where r is the radius of the sphere.

Surface Area of a Sphere:

where r is the radius of the sphere.

    We will create a Java program that takes the radius as input and calculates both the volume and surface area of a sphere.


    Java Code Example

    public class SphereCalculator {
        // Method to calculate volume of the sphere
        public static double calculateVolume(double radius) {
            return (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
        }
    
        // Method to calculate surface area of the sphere
        public static double calculateSurfaceArea(double radius) {
            return 4 * Math.PI * Math.pow(radius, 2);
        }
    
        public static void main(String[] args) {
            double radius = 5.0; // Example radius
    
            double volume = calculateVolume(radius);
            double surfaceArea = calculateSurfaceArea(radius);
    
            System.out.println("For a sphere with radius " + radius + ":");
            System.out.println("Volume = " + volume);
            System.out.println("Surface Area = " + surfaceArea);
        }
    }
    

    Output

    For a sphere with radius 5.0:
    Volume = 523.5987755982989
    Surface Area = 314.1592653589793
    

    Explanation

    1. Method for Volume Calculation
      • Uses the formula V=43πr3V = \frac{4}{3} \pi r^3V=34​πr3.
      • Math.pow(radius, 3) calculates .
      • Math.PI provides the value of π.
    2. Method for Surface Area Calculation
      • Uses the formula A=4πr2A = 4 \pi r^2A=4πr2.
      • Math.pow(radius, 2) calculates .
    3. Main Method Execution
      • We define a radius (e.g., 5.0).
      • We call both methods and print the calculated volume and surface area.

    Key Takeaways

    Uses Java’s Math class for precise calculations.
    Separates calculations into methods for better code organization.
    Easily adaptable – can take user input for dynamic radius values.