This is the Java Program to Find the Surface Area and Volume of a Sphere.
Given the dimensions of a sphere, find out its surface area and volume.
The surface area and volume of a sphere can be calculated using the formulas:
Surface Area = 4 * PI * (radius3) /3.
Volume = 4 * PI * (radius2).
Here is the source code of the Java Program to Find the Surface Area and Volume of a Sphere. The program is successfully compiled and tested using IDE IntelliJ Idea in Windows 7. The program output is also shown below.
//Java Program to Find the Surface Area and Volume of a Sphere
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Sphere {
// Function to calculate and print the surface area and volume of a sphere
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
double radius;
System.out.println("Enter the radius of the sphere");
try{
radius=Double.parseDouble(br.readLine());
}catch (Exception e){
System.out.println("An error occurred");
return;
}
if(radius<=0){
System.out.println("Wrong Input");
return;
}
System.out.println("Volume = " + (4*Math.pow(radius,3)*Math.PI)/3);
System.out.println("Surface area = " + (4*Math.PI*Math.pow(radius,2)));
}
}
1. In function main(), first, the radius of the sphere is taken as input.
2. The condition if(radius<=0) checks if the input is valid or not.
3. The print statement displays the surface area and volume of the sphere.
Time Complexity: O(1)
Case 1 (Simple Test Case): Enter the radius of the sphere 4.55 Volume = 394.56885292638566 Surface area = 260.15528764377075
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice Programming MCQs
- Check Programming Books
- Practice BCA MCQs
- Check Java Books
- Practice Information Technology MCQs