Guava - Math Utilities



Guava provides Mathematics related Utilities classes to handle int, long and BigInteger. Following is the list of useful utilities −

Useful Math Utilities

Sr.No Utility name & Description
1 IntMath

Math utility for int.

2 LongMath

Math utility for long.

3 BigIntegerMath

Math utility for BigInteger.

Example - Checked Operations of ints

GuavaTester.java

package com.tutorialspoint;

import java.math.RoundingMode;
import com.google.common.math.IntMath;

public class GuavaTester {

   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();
      tester.testIntMath();
   }

   private void testIntMath() {
      try {
         System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE));
         
      } catch(ArithmeticException e) {
         System.out.println("Error: " + e.getMessage());
      }

      System.out.println(IntMath.divide(100, 5, RoundingMode.UNNECESSARY));
      try {
         //exception will be thrown as 100 is not completely divisible by 3
         // thus rounding is required, and RoundingMode is set as UNNESSARY
         System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY));
         
      } catch(ArithmeticException e) {
         System.out.println("Error: " + e.getMessage());
      }
   }
}

Output

Run the GuavaTester and verify the output −

Error: overflow: checkedAdd(2147483647, 2147483647)
20
Error: mode was UNNECESSARY, but rounding was necessary

Example - Computing operations on Longs

GuavaTester.java

package com.tutorialspoint;

import java.math.RoundingMode;
import com.google.common.math.LongMath;

public class GuavaTester {

   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();
      tester.testLongMath();
   }

   private void testLongMath() {
      
      System.out.println("Log2(2L): " + LongMath.log2(2L, RoundingMode.HALF_EVEN));

      System.out.println("Log10(10L): " + LongMath.log10(10L, RoundingMode.HALF_EVEN));

      System.out.println("sqrt(100L): " + LongMath.sqrt(LongMath.pow(10L,2), RoundingMode.HALF_EVEN));

   }
}

Output

Run the GuavaTester and verify the output −

Log2(2): 1
Log10(10): 1
sqrt(100): 10

Example - BigInteger SQRT/Factorial Operations

GuavaTester.java

package com.tutorialspoint;

import java.math.BigInteger;
import java.math.RoundingMode;

import com.google.common.math.BigIntegerMath;

public class GuavaTester {

   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();
      tester.testBigIntegerMath();
   }
   
   private void testBigIntegerMath() {
      System.out.println("sqrt(100): " + BigIntegerMath.sqrt(BigInteger.TEN.multiply(BigInteger.TEN), RoundingMode.HALF_EVEN));
      System.out.println("factorial(5): "+BigIntegerMath.factorial(5));
   }
}

Output

Run the GuavaTester and verify the result.

sqrt(100): 10
factorial(5): 120
Advertisements