Using BigIntegers

As opposed to int or long, respectively 32-bit and 64-bit long, a BigInteger allows you to store an arbitrary big non-decimal number. It can also deal with bits and has the proper methods for that (and, shiftLeft, …)

Here’s a simple example that creates a BigInteger.

import java.math.*;
import java.util.*;
public class Main {
   static Random r = new Random();
   public static void main(String args[]) {
      BigInteger bi1 = new BigInteger(createLongNumber());
      BigInteger bi2 = new BigInteger(createLongNumber());
      BigInteger total = bi1.add(bi2);
      System.out.println("  " + bi1);
      System.out.println("+ " + bi2);
      System.out.println("= " + total);
   public static String createLongNumber() {
      StringBuffer total = new StringBuffer();
      for (int i=0; i<15; i++) {
      return total.toString();


+ 133287034081647952310168992582070726724673519674146599229384783108712083
= 206362008594983144063708670184694276786792940746284212158250267919830035

There are other ways to create a BigInteger. See the API for more information. For example, a BigInteger can be created containing a random number. We could have written the previous program using one of these constructors.