Java Program for finding Total surface area of a sphere. Here we have discussed about the various methods to calculate the Total Surface Area Of Sphere such as using the standard formula, Command Line Arguments and Class name in the main method. The compiler is added to each program mentioned with sample outputs.
Sphere is a completely round object in a 3-dimensional space.
The formula for calculating the Surface Area of a sphere with radius ‘r’ would be 4πr².
Using Standard Formula
1) We are calculating the total surface area of sphere using the standard formula is area=(4*22*r*r)/(7).
2) Read the radius value using scanner object sc.nextDouble() and store it in the variable r.Substitute the value in the formula and print the area value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; class TotalSurfaceAreaOfSphere { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the radius of sphere :"); double r=s.nextDouble(); double area=(4*22*r*r)/(7); System.out.println("Total SurfaceArea Of sphere is:" +area); } } |
Output:
1 2 |
Enter the radius of sphere :7 Total SurfaceArea Of sphere is:616.0 |
Using Command Line Arguments
1) In this program we are reading the radius value using command line arguments.
2) The values we will pass at run-time are called command line arguments, will store at string array “String args[]” of main method.
3) We are converting the value available at index 0 which is string, in to double using Double.parseDouble(). Here Double is wrapper class and store that value in the variable r, and calculate the area and print the total surface area of sphere
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Scanner; class TotalSurfaceAreaOfSphere1 { public static void main(String args[]) { double r=Double.parseDouble(args[0]); double area=(4*22*r*r)/(7); System.out.println("Total SurfaceArea Of sphere is:" +area); } } |
Output:
1 2 3 |
javac TotalSurfaceAreaOfSphere1.java java TotalSurfaceAreaOfSphere1 7 Total SurfaceArea Of sphere is:616.0 |
Using Class Name in the Main Method
1)We are calling the static method with its class name in the main method as TotalSurfaceAreaOfSphere.area(r); then static method executed and returns the area value and that value will be assigned to a and print the total surface area of the sphere.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Scanner; class TotalSurfaceAreaOfSphere { public static void main(String args[]) { Scanner s= new Scanner(System.in); System.out.println("Enter the radius of sphere1:"); double r=s.nextDouble(); double a= TotalSurfaceAreaOfSphere.area(r); System.out.println("TotalSurface Area Of Sphere is:" +a); } public static double area(double r) { double area=(4*22*r*r)/(7); return area; } } |
Output:
1 2 |
Enter the radius of sphere :7 Total SurfaceArea Of sphere is:616.0 |
More Programs: