Table of Contents
The Pi
is a constant value in Mathematics that represents a floating-point value 3.1415
. It is mostly used in geometry to calculate area, circumference, volume, etc. If you have studied geometry in your academic, then you may be aware of use of Pi such as calculating area require this constant value.
In Java, when we do geometric calculations, then we need this constant and for that, we have mainly two options either we create a constant and assigned 3.1415
value to it or use PI constant of Math
class. Yes, Java provides a Math
class that contains PI
constant. So, Let’s see some examples to understand the use of PI in Java.
PI Constant in Java
Here, we created a constant our own and assigned a value to it. We declared it as final
so, cannot be changed. Here, we are calculating the area and circumference of circle by using the created PI constant.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import java.util.Scanner; public class Main { public static void main(String args[]) { final double PI = 3.14; System.out.println("Enter radius : "); Scanner sc = new Scanner(System.in); double r = sc.nextDouble(); double CircleArea = PI*(r*r); System.out.println("Area is : "+CircleArea); double CircleCircumference = 2*(PI*r); System.out.println("Circumference is : "+CircleCircumference); } } |
Output
5
Area is : 78.53
Circumference is : 31.41
PI Constant in Java Math Class
Since Math class provides PI constant, we can use it to perform geometric calculations. Here, we are getting area and circumference of area using Math class. See the example and output below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.util.Scanner; public class Main { public static void main(String args[]) { System.out.println("Enter radius : "); Scanner sc = new Scanner(System.in); double r = sc.nextDouble(); double CircleArea = Math.PI*(r*r); // Match class System.out.println("Area is : "+CircleArea); double CircleCircumference = 2*(Math.PI*r); System.out.println("Circumference is : "+CircleCircumference); } } |
Output:
5
Area is : 78.53
Circumference is : 31.41
That’s all about PI
in java.