Basic Math Functions
Explore basic Java Math functions such as absolute value, power, square root, random number generation, minimum, maximum, and rounding. Understand how to use these methods to perform common mathematical computations in Java, helping you build essential programming skills for the AP Computer Science A exam.
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.
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, orlongtype 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 of the second parameter.
Run the program below.
Look at line 5. We call the pow() function with ...