Math Methods

The Math Class

java.lang.Math has static methods for common calculations. You call them on the class itself: Math.max(a, b). No import is needed.

MethodMeaningExampleResult
Math.max(a, b)larger valueMath.max(4, 9)9
Math.min(a, b)smaller valueMath.min(4, 9)4
Math.abs(x)absolute valueMath.abs(-7)7
Math.pow(a, b)a to the power b (double)Math.pow(2, 10)1024.0
Math.sqrt(x)square rootMath.sqrt(144)12.0
Math.cbrt(x)cube rootMath.cbrt(27)3.0
Math.PIconstant pi3.141592653589793

Example

Example

public class Main {
    public static void main(String[] args) {
        System.out.println(Math.max(120, 95));
        System.out.println(Math.min(-3, 2));
        System.out.println(Math.abs(-250));
        System.out.println(Math.pow(2, 10));
        System.out.println(Math.sqrt(64));
        double radius = 7;
        double area = Math.PI * Math.pow(radius, 2);
        System.out.println("Circle area: " + area);
        // distance between points (1,2) and (4,6)
        System.out.println(Math.hypot(4 - 1, 6 - 2));
    }
}

Output

120
-3
250
1024.0
8.0
Circle area: 153.93804002589985
5.0