Java 8 Math New Methods

I just announced the new Spring 5 modules in REST With Spring:

1. Introduction

Usually, when we think about the new features that came with version 8 of Java, functional programming and lambda expressions are first things that come to mind.

Nevertheless, besides those big features there’re others, maybe having a smaller impact but also interesting and many times not really well known or even covered by any review.

In this tutorial, we’ll enumerate and give a little example of each of the new methods added to one of the core classes of the language: java.lang.Math.

2. New *exact() Methods

First, we have a group of new methods that extend some of the existing and most common arithmetic operations.

As we’ll see, they’re quite self-explanatory, as they have exactly the same functionality than the methods they derive from but with the addition of throwing an exception in case, the resulting value overflows the max or min values of their types.

We can use these methods with both integers and longs as parameters.

2.1. addExact()

Adds the two parameters, throwing an ArithmeticException in case of overflow (which goes for all *Exact() methods) of the addition:

The second example requires an explanation as it’s not obvious: The overflow is due to the Integer.MIN_VALUE being −2.147.483.648, and on the other side the Integer.MAX_VALUE being 2.147.483.647 so the returned value doesn’t fit into an Integer by one unit.

3. Other Methods

3.1. floorDiv()

Divides the first parameter by the second one, and then performs a floor() operation over the result, returning the Integer that is less or equal to the quotient:

Math.floorDiv(7, 2)); // returns 3

The exact quotient is 3.5 so floor(3.5) == 3.

Let’s look at another example:

Math.floorDiv(-7, 2)); // returns -4

The exact quotient is -3.5 so floor(-3.5) == -4.

3.2. modDiv()

This one is similar to the previous method floorDiv(), but applying the floor() operation over the modulus or remainder of the division instead of the quotient:

Math.modDiv(5, 3)); // returns 2

As we can see, the modDiv() for two positive numbers is the same as % operator. Let’s look at a different example:

Math.modDiv(-5, 3)); // returns 1

It returns 1 and not 2 because floorDiv(-5, 3) is -2 and not -1.

3.3. nextDown()

Returns the immediately lower value of the parameter (supports float or double parameters):

4. Conclusion

In this article, we’ve described briefly the functionality of all the new methods added to the class java.lang.Math in the version 8 of the Java platform and also seen some examples of how to use them.