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.
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.
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);
}
}
For a sphere with radius 5.0:
Volume = 523.5987755982989
Surface Area = 314.1592653589793
Math.pow(radius, 3)
calculates r³
.Math.PI
provides the value of π.Math.pow(radius, 2)
calculates r²
.5.0
).✅ 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.