Math.PI Java Example - PI in Java

Math.PI Java Example - PI in Java

In Java, we can use the Math.PI constant defined in the java.lang.Math class to retrieve and use the PI (*) value. In mathematics, Math.PI is a final double-type variable with a double value that is closest to *, the circumference-to-diameter ratio of a circle.

"public static final double PI = 3.14159265358979323846;"

Since it is a static variable so, we can directly access it through its class name like Math.PI. Example:-

"class Test {

  public static void main(String[] args) {

     double x = Math.PI;

     System.out.println(x);

  }

}"

Output:-

PI can be accessed without calling through its class name if we import Math class statically.

"import static java.lang.Math.*;

class Test {

  public static void main(String[] args) {

    System.out.println(PI);

  }

}"

"import static java.lang.Math.*;" imports all static members of the Math class. We can, however, use the "import static java.lang.Math.PI;" statement to import only the PI variable from the Math class and not other static methods and variables of the Math class.

Read more about:- static import in Java.

"import static java.lang.Math.PI;

class Test {

  public static void main(String[] args) {

     System.out.println(PI);

  }

}"

Using PI in Java

First, obtain the PI value by calling the PI variable of the Math class, and then use it in the program. Here are some examples:-

Java Program for Finding the Area of a Circle Using Math.PI

"class Area {

  public static void main(String[] args) {

     double radius = 10;

     double area = Math.PI*radius*radius;

     System.out.println(area);

  }

}" 

Output:-

"314.1592653589793"

We are accessing the PI value directly through the class name in this example. The PI value can be obtained without the class name by using the import statement.

"import static java.lang.Math.*;

class Area {

  public static void main(String[] args) {

     double radius = 10;

     double area = PI*radius*radius;

     System.out.println(area);

  }

}"

Although we only need PI value in this example, we are importing all the static methods and variables of the Math class, which are not needed in this program. In order to get the * value, it is better to import only the PI variable of the Math class.

In this case, only the PI variable is available to the class, other static methods and variables will not be accessible.

"import static java.lang.Math.PI;

class Area {

  public static void main(String[] args) {

     double radius = 10;

     double area = PI*radius*radius;

     System.out.println(area);

  }

}"

Please share this post with your friends if you liked it. Would you like to share additional information about the topic discussed above or do you find anything incorrect? Comment below. We appreciate your feedback!