Basic mathematical functions

Java Math class

Java provides the Math class for basic mathematical operations. From rounding and root extraction to angle functions, many common mathematical calculations are available. The Math class is included in the standard Java library and therefore does not need to be imported.

Example 1

public class BasicFunctions {
	public static void main(String[] args) {
		int min, max, abs;

		min = Math.min(2, 4);
		max = Math.max(2, 4);
		abs = Math.abs(-20);

		System.out.println("Max value: " + max);
		System.out.println("Min value: " + min);
		System.out.print("abs value of -20 is: " + abs);
	}
}
Output
Max value: 4
Min value: 2
abs value of -20 is: 20

Example 2

public class Cube {
    public static void main(String[] args) {
        double sqrt, cubic, power;

        sqrt = Math.sqrt(81);
        cubic = Math.cbrt(216);
        power = Math.pow(2, 4);

        System.out.println("Square: " + sqrt);
        System.out.println("Cubic: " + cubic);
        System.out.println("Power: " + power);
    }
}
Output
Square: 9.0
Cubic: 6.0
Power: 16.0