Java Program to find Volume and Surface Area of a Cylinder
In this tutorial, we will see how to write a java program to find the volume and surface area of any given cylinder. Before we begin, let us first see the definition and formulas used to calculate the surface area of a cylinder and volume of a cylinder.
Surface Area of a Cylinder
If we know the radius and height of the cylinder then we can calculate the surface area of a cylinder by using the following formula:
Surface Area of a Cylinder = 2πr(r+h)
Volume of a Cylinder
The amount of space inside the given cylinder is known as Volume. If we know the height of a cylinder then we can calculate the volume as follows:
Volume of a Cylinder = πr²h
Java Code to find the volume and surface area of a cylinder
import java.util.Scanner; public class prog { public static void main(String[] args) { Scanner obj = new Scanner(System.in); System.out.println("Radius : "); double r = obj.nextDouble(); System.out.println("Height : "); double hgt = obj.nextDouble(); double surface_area = 2 * Math.PI * r * (r + hgt); double vol = Math.PI * r * r * hgt; System.out.println("Surface area = " + surface_area); System.out.println("Volume = "+ vol); } }
We will prompt the user to enter the values of radius and base of the cylinder whose surface area and volume is desired. For that, we will use the Scanner class to get user input.
- java.util package contains Scanner class
After creating an instance of Scanner class, we will use the nextDouble() method to read these two values since they will be floating-point numbers.
Using these values, we will calculate the Volume of a Cylinder and Surface Area of a Cylinder 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 Height : 3 Surface area = 175.92918860102841 Volume = 150.79644737231007
Also read,
Calculating Area of a Trapezoid using Java
Is the area of the cylinder and surface area of cylinder are same?
Yes it is similar. But we use surface area as it indicates the right term.
A=2πrh+2πr2
If you want to get only the rounded surface part then it will be 2πrh only.