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...!!! Share on X

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...!!! Share on X

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

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester. He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    http://Techndeck.com deepak.rkgit@gmail.com Verma Deepak