CodeBlanks Logo Icon CodeBlanks

Math constants

Learn built-in constants like Math.PI.

Math constants

Java's Math class provides mathematical constants and methods. The best-known constants are Math.PI (the number pi) and Math.E (the number e). These constants are static final and can be used directly.

Example: double area = Math.PI * radius * radius;. Here Math.PI gives the number pi; approximately 3.14159. It is used to calculate a circle's area. Math.E is the natural logarithm base; approximately 2.71828. You do not need to define these constants yourself; the Math class provides them ready. Math also contains methods like abs, max and sqrt; these are static and called through the class name.

Math methods

The Math class also provides mathematical methods: Math.abs for absolute value, Math.max for the largest, Math.sqrt for square root. All are static and called through the class name.

Example: int absVal = Math.abs(-5); returns five. int big = Math.max(3, 7); returns seven. double root = Math.sqrt(16); returns four. These methods are called as Math.methodName(...) without an instance. The Math class's constructor is hidden; new Math() cannot be written. All members are static. This is the typical design of utility classes.

Practice Use Math constants and methods

In a main method calculate a circle's area. Write double radius = 5.0. Calculate the area with double area = Math.PI * radius * radius;. Get the absolute value with int absVal = Math.abs(-10);. Print the area and absVal values on separate lines.

Starter code

Main.java
// Use Math in main
// Calculate circle area and absolute value
// Print results

Sample solution

Main.java
public class Main {
    public static void main(String[] args) {
        double radius = 5.0;
        double area = Math.PI * radius * radius;
        int absVal = Math.abs(-10);
        System.out.println(area);
        System.out.println(absVal);
    }
}

Expected output

78.53981633974483
10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which constant is used for a circle's area?

  • Math.PI Correct answer
  • Math.E
  • Math.AREA
  • Math.RADIUS

Explanation: Math.PI gives the number pi; it is used in circle area.

2 Complete the Math.abs call

Question
int result = ____;
Answer
int result = Math.abs(-5);

Explanation: Math.abs gives the absolute value.

3 Match Math members

Term Meaning
Math.abs Absolute value
Math.max Largest
Math.sqrt Square root
Math.PI Pi number

All lessons in Intermediate