What is Java Math ? How it works ?

What is Java Math ? How it works ?

1. Introduction

In this tutorial, we're going to describe the Math class that provides helpful static methods for performing numeric operations such as exponential, logarithm, etc.

2. Basic Math Functions

The first set of methods we'll cover are the basic math functions such as the absolute value, the square root, the maximum or the minimum between two values.

2.1. abs()

The abs() method returns the absolute value of a given value:

Math.abs(-5); // returns 5

Likewise, of others that we'll see next, abs() accepts as a parameter an int, long, float or double and returns the relative one.

2.2. pow()

Calculates and returns the value of the first argument raised to the power of the second one:

Math.pow(5,2); // returns 25

We discuss this method in more detail in here.

2.3. sqrt()

Returns the rounded positive square root of a double:

Math.sqrt(25); // returns 5

If the argument is NaN or less than zero, the result is NaN.

2.4. cbrt()

Similarly, cbrt() returns the cube root of a double:

Math.cbrt(125); // returns 5

2.5. max()

As the method's name suggests, it returns the maximum between two values: