Using BigInteger in Java

For handling numbers, Java provides built-in types such as int and long. However these types are not useful for very large numbers. When you do mathematical operations with int or long types and if the resulting values are very large, the type variables will overflow causing errors in the program.

Java provides a custom class named BigInteger for handling very large integers (which is bigger than 64 bit values). This class can handle very large integers and the size of the integer is only limited by the available memory of the JVM. However BigInteger should only be used if it is absolutely necessary as using BigInteger is less intuitive compared to built-in types (since Java doesn't support operator overloading) and there is always a performance hit associated with its use. BigInteger operations are substantially slower than built-in integer types. Also the memory space taken per BigInteger is substantially high (averages about 80 bytes on a 64-bit JVM) compared to built-in types.

Another important aspect of BigInteger class is that it is immutable. This means that you cannot change the stored value of a BigInteger object, instead you need to assign the changed value to a new variable.

Java BigInteger Example

The following BigInteger example shows how a Java BigInteger can be created and how various arithmetic operations can be performed on it,

import java.math.BigInteger;

public class BigIntegerDemo {

    public static void main(String[] args) {
        
        BigInteger b1 = new BigInteger("987654321987654321000000000");
        BigInteger b2 = new BigInteger("987654321987654321000000000");
        
        BigInteger product = b1.multiply(b2);
        BigInteger division = b1.divide(b2);
        
        System.out.println("product = " + product);
        System.out.println("division = " + division);  // prints 1
    
    }
}

 

Computing Factorial Using BigInteger

Computation of factorial is a good example of numbers getting very large even for small inputs. We can use BigInteger to calculate factorial even for large numbers!

import java.math.BigInteger;
public class BigIntegerFactorial {

    public static void main(String[] args) {
        calculateFactorial(50);
    }
    public static void calculateFactorial(int n) {
        
        BigInteger result = BigInteger.ONE;
        for (int i=1; i<=n; i++) {
            result = result.multiply(BigInteger.valueOf(i));
        }
        System.out.println(n + "! = " + result);
    }
    
}

The factorial output for an input value of 50 is,

50! = 30414093201713378043612608166064768844377641568960512000000000000