Beginners Programs :

Java BigInteger Class – Tutorial & Examples | JavaTutorials

Whats is Java BigInteger?

The class BigInteger is in the package java.math

In Java, we have 4 data types to deal with integer type data. Those are byte, short, int and long.

  • With byte, we can store numbers up to 127.
  • With short, we can store numbers up to 32767.
  • With int, we can store numbers up to 2147483647.
  • With long, we can store numbers up to 9223372036854775807.

So for most of our integer calculations, these data types are good enough.

Sometimes, we may need to work with integers with 20 or more digits. In that case, these existing data types are not sufficient. BigInteger is the answer in these situations.

BigInteger Class In Java

We have many constructors for this class. One of the simple ones will take a String as an argument where the string is treated as integer internally. There is no limit on the size (number of digits) of the number.

Example:

We cannot use the operators like + and – directly on the BigInteger objects. But we have methods to perform add, subtract, etc on these objects.

Example:

To perform relational operations on BigIntegers, we can use methods like equals() and compareTo(). We know equals() method returns true or false and compareTo() method returns -1 or 0 or 1.

The valueOf() is a static method in BigInteger that takes a normal integer as argument and returns its equivalent BigInteger object.

Example:

In this example, we have taken smaller values for simplicity. But there is no limit on its size. The class has some mathematical methods like pow() and gcd() that calculate Power-Of and Greatest-Common-Divisors.

Similarly, we have methods to perform bitwise operations (and, or, xor, not, etc) also on the values. All the following mentioned methods return a BigInteger object.

Example:

Points To Note

Internally the values are stored in normal 2’s complement notation only  (generally, the integers in Java are also stored in this format only).

On BigIntegers also, a division by 0 results in ArithmeticException.

Some more constructors:

BigInteger(byte[]):

This constructor takes a byte array and forms a number by appending all the bits of each byte (as each value is stored as an 8-bit sequence).

Example:

In this example, the values in the array are 4 and 8. If we place bit sequences, those will look like

00000100 00001000

When all the bit sequence is considered as a single number it becomes 1032 (1024+8)

BigInteger(String, int)

This method takes a String as the first argument which consists of a digit sequence and an integer as the second argument that represents radix of the specified String.

It means, if the system should treat the String as a binary number (set of bits in binary number system) then the second argument should be 2.

If the system should treat the string as a hexadecimal number then the second argument should be 16.

Example: