BigInteger
An integer of any size — for when even long is not enough.
Available since: Java 1.1
Syntax
public class BigInteger extends Number implements Comparable<BigInteger>Examples
30 factorial does not fit in a long:
void main() {
BigInteger result = BigInteger.ONE;
for (int i = 2; i <= 30; i++) {
result = result.multiply(BigInteger.valueOf(i));
}
IO.println(result);
}Output:
265252859812191058636308480000000Power, remainder and comparison:
void main() {
var big = new BigInteger("2").pow(100);
IO.println(big);
IO.println(big.mod(BigInteger.TEN));
IO.println(big.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0);
}Output:
1267650600228229401496703205376
6
trueNotes
The +, *, < operators do not work with BigInteger — use the methods add(), multiply(), compareTo(). Objects are immutable; each method returns a new number. Ready constants: BigInteger.ZERO, ONE, TWO, TEN.
See also
- BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
- Integer.MAX_VALUE — The largest int value; its partner is Integer.MIN_VALUE.
- Long.parseLong() — Converts a string with an integer to a long — for numbers that do not fit in an int.
- Math.pow() — Raises a number to a power.
Related recipes
In the tutorial
- Primitive types — Java's eight primitive types: int, long, double, float, char, boolean, byte and short, their ranges and overflow.