Basic Math Functions

Get an overview of the basic Math functions.

The Math class has many methods that allow you to perform mathematical operations on numbers. Let’s start covering the basic methods below.

Finding the absolute value

Java provides the abs() method, which returns the absolute value of the argument passed to it. The absolute value is the positive value of a number.

Run the program below.

Press + to interact
class AbsoluteValue
{
public static void main(String args[])
{
// Declaring variables
int i1 = 2;
int i2 = -2;
// Calling abs() method on them
System.out.println(Math.abs(i1));
System.out.println(Math.abs(i1));
}
}

We declare two integers: i1 and i2. Look at line 10. We call the abs() function with i1 as an argument. It prints 22. The absolute value of a positive value is the value itself. In the next line, we call the abs() function with i2 as an argument. It prints 22 after removing the - (negative) sign.

⚙️ Note: Like int, we can also pass the float, double, or long type variable as a parameter to the Math.abs() function.

Raising the number to a power

Java provides the pow() method, which accepts a total of two double type parameters, and returns the value (double type) of the first parameter raised to the power ...