Java program to calculate surface area and volume of a sphere
In this tutorial, we will see how to write a java program to find the volume and surface area of any given sphere. Before we begin, let us first see the definition and formulas used to calculate the surface area and volume of a sphere.
Surface Area of a Sphere
If we know the radius the sphere then we can calculate the surface area of a sphere by using the following formula:
Surface Area of a Cylinder = 4 * π* (radius3) /3
Volume of a Sphere
The amount of space inside the given sphere is known as Volume. We can calculate the volume as follows:
Volume of a Sphere = 4 * π * (radius2)
Java Code to find the surface area and volume of a sphere
Following is the source code of our java program to calculate the surface area and volume of the sphere.
import java.io.*; public class Prog{ public static void main(String[] args)throws IOException { BufferedReader ob = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Radius: "); double radius=Double.parseDouble(ob.readLine()); if(radius<=0){ System.out.println("\nInvalid input"); return; } double vol= (4*Math.pow(radius,3)*Math.PI)/3; double sa= (4*Math.PI*Math.pow(radius,2)); System.out.println("\nVolume = " + vol); System.out.println("Surface area = " + sa); } }
We will prompt the user to enter the values of radius of the sphere whose surface area and volume is desired. For that, we will use the BufferedReader class to get user input.
After creating an object of BufferedReader class, we will use the ob.readLine() method to read the value as a string and then parse it into a double type since radius will be a floating-point number.
- If the user enters the value of radius less than zero, we will not proceed with the calculation. A message will be displayed and the program will be terminated using the return statement.
Using this value, we will calculate the Volume and Surface Area of a Sphere as per the formula.
We have used the mathematical formula for our calculation.
Finally, we display the values of volume and surface area using print statements.
Output:
Radius : 4 Volume = 268.082573106329 Surface area = 201.06192982974676
Also read,
Leave a Reply