Looking for java Answers? Try Ask4KnowledgeBase
Looking for java Keywords? Try Ask4Keywords

Java LanguageBigInteger


Introduction

The BigInteger class is used for mathematical operations involving large integers with magnitudes too large for primitive data types. For example 100-factorial is 158 digits - much larger than a long can represent. BigInteger provides analogues to all of Java's primitive integer operators, and all relevant methods from java.lang.Math as well as few other operations.

Syntax

  • BigInteger variable_name = new BigInteger("12345678901234567890"); // a decimal integer as a string
  • BigInteger variable_name = new BigInteger("1010101101010100101010011000110011101011000111110000101011010010", 2) // a binary integer as a string
  • BigInteger variable_name = new BigInteger("ab54a98ceb1f0800", 16) // a hexadecimal integer as a string
  • BigInteger variable_name = new BigInteger(64, new Random()); // a pseudorandom number generator supplying 64 bits to construct an integer
  • BigInteger variable_name = new BigInteger(new byte[]{0, -85, 84, -87, -116, -21, 31, 10, -46}); // signed two's complement representation of an integer (big endian)
  • BigInteger variable_name = new BigInteger(1, new byte[]{-85, 84, -87, -116, -21, 31, 10, -46}); // unsigned two's complement representation of a positive integer (big endian)

Remarks

BigInteger is immutable. Therefore you can't change its state. For example, the following won't work as sum won't be updated due to immutability.

BigInteger sum = BigInteger.ZERO;
for(int i = 1; i < 5000; i++) {
   sum.add(BigInteger.valueOf(i));  
}

Assign the result to the sum variable to make it work.

sum = sum.add(BigInteger.valueOf(i));

Java SE 8

The official documentation of BigInteger states that BigInteger implementations should support all integers between -22147483647 and 22147483647 (exclusive). This means BigIntegers can have more than 2 billion bits!