Exact Methods on Java Program

Compiled By Unknown - No Comments

Exact methods. The Math class provides "exact" methods. These do what we expect (add, subtract, multiply) but throw an ArithmeticException when the result overflows.

So: In a computation where overflow would be disastrous, these methods help check that the program is correct.

Tip: An exception is easier to debug than an unusual result from a mathematical computation, which may just cause incorrect output.

Java program that uses addExact, exact methods

import java.lang.Math;

public class Program {
    public static void main(String[] args) {

 // Use exact methods.
 int result1 = Math.addExact(1, 1);
 int result2 = Math.addExact(100, 1);
 int result3 = Math.subtractExact(100, 1);
 int result4 = Math.multiplyExact(5, 4);
 int result5 = Math.incrementExact(2);
 int result6 = Math.decrementExact(1000);
 int result7 = Math.negateExact(100);
 // Display our results.
 System.out.println(result1 + " " + result2 + " " + result3 + " "
  + result4 + " " + result5 + " " + result6 + " " + result7);

 // An ArithmeticException is thrown if a number overflows.
 try {
     int invalid = Math.multiplyExact(Integer.MAX_VALUE, 100);
 } catch (Exception ex) {
     System.out.println(ex);
 }
    }
}

Output

2 101 99 20 3 999 -100
java.lang.ArithmeticException: integer overflow

Tags:

No Comment to " Exact Methods on Java Program "