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.
class AbsoluteValue{public static void main(String args[]){// Declaring variablesint i1 = 2;int i2 = -2;// Calling abs() method on themSystem.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 . 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 after removing the (negative) sign.
⚙️ Note: Like
int
, we can also pass thefloat
,double
, orlong
type variable as a parameter to theMath.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 ...