Skip Top Navigation Bar

Using the Math Class

Currently, we have covered the operators of a four function calculator with the ability to add, subtract, multiply, and divide. And, we added that new operator to compute the remainder, the modulus operator %. However, there are a lot more math functions that we will want to use if we are going to create simulations, physics related games, or analyze data, just to name a few.

Good news, Java have a Math class.

The methods in the Math class are all static methods. Static methods belong to the class instead of to an object of the class and are called using the class name.

Methods that are part of the AP Computer Science A Java subset are denoted by the APCSA label.

Math Methods

We are going to share some common math methods, but you can find a complete list of methods in the Math API.

static int abs(int a) and static double abs(double a)

This method returns the absolute value of a. There are also abs methods for other data types too, such as double.

static double ceil(double a) & static double floor(double a)

The ceil method returns the next largest double that is equal to a whole number. In other words, it rounds up. The floor method return the next smalled double that is equal to a whole number. In other words, it rounds down or truncates the double.

static int max(int a, int b)

This method returns the greater of the two values a or b. There are additional max methods that take other data types, such as double.

static int min(int a, int b)

This method returns the smaller of the two values a or b. There are additional min methods that take other data types, such as double.

static double pow(double a, double b)

This method returns the value of a raised to the b power.

static double random()
This method returns a random value between `0.0` (inclusive) and `1.0` (exclusive).

The following formula can be used to adjust the range of possible values to be an int between two values.

int randomValue = (int)(Math.random() * numberOfPossiblities) + lowestNumber;

Note the placement of the parenthesis is really important. You will want the computer to first multiply by the numberOfPossibilities before casting to an int value. If you cast Math.random() to an int, you will always get 0, because all of the possible values are between 0.0 (inclusive) and 1.0 (exclusive). They are all decimal values that will truncate to 0.

static double sqrt(double a)

This method returns the square root of a.

There are many other methods including those that compute trigonometric functions.

Resources