Using class Math

Math is yet another class belonging to the core set of the Java programing language.

exercise No. 119

Using constants from java.lang.Math. Create comment in forum

Q:

In Exercise Calculating a circle's area avoiding accidental redefinition you calculated a given circle's area protecting variables against accidental redefinition using the final modifier:

public static void main(String[] args) {

  double radius = 2.31;         // A circle having a radius (given e.g. in mm).
  final double PI = 3.1415926;  // Creating PI as a constant (non-modifiable/
                                // assignable) variable.

  final double area = PI * radius * radius;
  System.out.println(area);
}

You may have wondered why you had to punch in the value of π yourself. Actually Java predefines constants in java.lang.Math class. Read its documentation to rewrite your code thereby replacing your own variable pi's definition .

Tip

You may want to read the Static Members and Java Packages sections of [Kurniawan].

A:

The short answer simply is:

public static void main(String[] args) {

  double radius = 2.31;       // A circle having a radius (given e.g. in mm).

  final double area = Math.PI * radius * radius;
  System.out.println(area);
}

In case you bother about using the somewhat clumsy Math.PI expression rather than just using PI itself some syntactic sugar is on offer by means of a static import statement:

import static java.lang.Math.PI;

public class CircleAreaCalculator {

   public static void main(String[] args) {

      double radius = 2.31; // A circle having a radius (given e.g. in mm).

      final double area = PI * radius * radius; // This actually refers to Math.PI
      System.out.println(area);
   }
}

We dig a little deeper to fully understand the underlying concepts. Obtaining a JDK's source code and browsing its implementation Math.java reveals:

/*
 * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
 * ...
 */

package java.lang;
...

public final class Math {

...
    /**
     * The {@code double} value that is closer than any other to
     * <i>pi</i>, the ratio of the circumference of a circle to its
     * diameter.
     */
    public static final double PI = 3.14159265358979323846;
...

This accounts for using the expression Math.PI.

The careful reader may have expected an import statement in order to use the Math class:

import java.lang.Math; // Optional: Classes from java.lang are imported
                       // implicitely as per the Java language specification.

public class CircleAreaCalculator {

   public static void main(String[] args) {

      double radius = 2.31; // A circle having a radius (given e.g. in mm).

      final double area = Math.PI * radius * radius;
      System.out.println(area);
   }
}

But since the Math class belongs to the java.lang package it is present by default and does not have to be imported.