Programming is used to solve real-life problems that may include implementing different mathematical formulas. And these formulas are used in various mathematical constants and functions.
What is Pi?
The Pi is a constant value used in different formulas in geometry like calculating circumference, area, volume, etc. It is a mathematical constant that is defined as the circumference of a circle divided by its diameter.
The value of a constant pi is approximately 3.14. Java provides built-in constant field of Pi that belong to java.lang,Math class.
The following program shows the use of constant value pi without using the built-in constant field.
Radius of circle: 5 Area of circle is: 78.5 Circumference of circle is: 31.400000000000002
In the above code, the pi value is set to 3.14 using a final double variable pi. And the area and circumference are calculated and displayed.
Pi in Java
The Java Math class provides methods for implementing numeric operations like logarithm, square root, trigonometric functions, minimum or maximum number.
The pi is a field defined in the Math class as a static variable of type double. To access this constant the Java program has to import java.lang.Math class. As it's a static variable we can directly access it using the Math.PI into the Java program.
The following program shows the use of Math.PI variable in a Java program.
Radius of circle: 5 Area of circle is: 78.53981633974483 Circumference of circle is: 31.41592653589793
In the above code, the Math.PI is used instead of declaring a local variable. And the area and circumference of the circle is displayed on the console.
Program for calculating the volume of a cylinder using built-in variable and user-defined variable
Volume of cylinder by using built-in variable PI is: 1178.0972450961724 Volume of cylinder by using the user-defined Pi value is: 1177.5
The above Java code demonstrates both the ways of using Pi constant in a program. The area of a cylinder is calculated using multiplication operation and displayed using both methods.
In this article, we have discussed the mathematical constant Pi, how it can be implemented in a Java program and a program to demonstrate it.