Java Code Example: volume and surface area of a ball

The VolumeSurfaceBall class calculates the volume and surface area of a sphere with a given radius. It uses the Math library in Java to calculate the result. The Math.pow(base, exponent) function returns the result of raising base to the power exponent.

The getVolume method calculates the volume of the sphere using the formula (4 * Math.PI * Math.pow(r, 3)) / 3, where r is the radius.

The getSurfaceArea method calculates the surface area of the sphere using the formula 4 * Math.PI * Math.pow(r, 2).

In the main method, a Scanner object is used to read the radius of the sphere from the user. The values of the volume and surface area are then computed using the getVolume and getSurfaceArea methods and displayed to the user using the println method. The String.format("%1.2f", number) method is used to format the result to 2 decimal places.

import java.util.Scanner;

class VolumeSurfaceBall {
    static double getVolume(double r) {
        // Math.pow(base, exponent): Returns base raised to the power exponent
        return (4 * Math.PI * Math.pow(r, 3)) / 3;
    }

    static double getSurfaceArea(double r) {
        return 4 * Math.PI * Math.pow(r, 2);
    }

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        double r, area, volume;

        System.out.print("Please enter radius: ");
        r = reader.nextDouble();
        reader.close();

        area = getSurfaceArea(r);
        volume = getVolume(r);

        System.out.println("Volume: " + String.format("%1.2f", volume));
        System.out.println("Surface Area: " + String.format("%1.2f", area));
    }
}
Output
Please enter radius: 2.5
Volume: 65.45
Surface Area: 78.54