JAVA 8 – New Math Methods

Whenever we talk about Java 8, what comes in mind most often is ‘Lambda‘ and ‘Streams‘. Am I wrong? I don’t think so. Although these are the most prominent features that came with Java 8, there are other key things that came along too. So, we are going to talk about these less prominent but powerful and important features for any Java developer. These features are nothing but the changes that have been made in the ‘Math‘ class to support ‘Exact Arithmetic‘.

Java 8 introduced new methods in the java.lang.Math class to handle overflows and throws ArithmeticException. These methods are: 

    1. addExact
    2. substractExact
    3. multiplyExact
    4. incrementExact
    5. decrementExact
    6. negateExact

All these methods take either int & long as arguments.

 

Java 8 Arithmetic Exact Methods...!!! Click To Tweet

Let’s discuss first what these methods are:

1. addExact Adding two arguments using the exact method but will throw an arithmetic exception if an overflow occurs. 

 

2. subtractExact Subtracting the second argument from the first one but will throw an arithmetic Exception if an overflow occurs. 

 

3. incrementExact Incrementing the argument by one but will throw an arithmetic exception if an overflow occurs. 

 

4. decrementExact Decrementing the argument by one but will throw an arithmetic exception if an overflow occurs. 

 

5. multiplyExact Multiply the first and second argument but will throw an arithmetic exception if an overflow occurs. 

 

6. negateExact Alter the sign of the argument but will throw an arithmetic exception if an overflow occurs. 

 

Example:

That’s it. Java 8 Math Methods gives so much convenience to Java developers in order to handle exceptions in such situations that we described above. 

 

Java 8 Arithmetic Exact Methods...!!! Click To Tweet

Do you like this Post? – then check my other helpful posts:

Other Useful References:

 

Related Posts:

[wcp-carousel id=”5342″]

Leave a Reply

Your email address will not be published.Required fields are marked *

Facebook Twitter Instagram YouTube