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.

Main.java:

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++) {
         total.append(Math.abs(r.nextInt()));
      }
  
      return total.toString();
   }
}

outputs:

  730749745133351917535396776026235500621194210721376129288654848111179522
31934740694371855592481952346363130735653456760027617802679261977162139
+ 133287034081647952310168992582070726724673519674146599229384783108712083
237393757881612001996413136278288312261653333848082459044525261007117879
= 206362008594983144063708670184694276786792940746284212158250267919830035
469328498575983857588895088624651442997306790608110076847204522984280018

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.