Pi Constant in Java

Lovey Arora Oct 12, 2023
  1. Use the final Keyword to Create a Pi Constant in Java
  2. Use the Math.PI to Get the Value of Pi in Java
Pi Constant in Java

In mathematics, p is a constant value that is equal to 3.1415. This constant is used in many formulas to calculate surface areas, volumes, etc.

This tutorial demonstrates how to get the value for the pi constant in Java.

Use the final Keyword to Create a Pi Constant in Java

We can use the final keyword to create constants in Java. This way, its value cannot get changed throughout the program.

See the code given below.

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:

Enter radius : 
2
Area is : 12.56
Circumference is : 12.56

Here, we have first created the variable PI, which contains the value of pi, and declared it as a constant using the final keyword. Then, we further use the newly created constant to calculate the circumference and area.

Use the Math.PI to Get the Value of Pi in Java

The Math class in Java already has a constant created for the value of pi. We can access this constant using Math.PI. This way, we get the exact value for the constant.

For example,

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:

Enter radius : 
Area is : 12.566370614359172
Circumference is : 12.566370614359172

Related Article - Java Math