Scrivio Interview library
InternalsIntermediate7 min read · updated 12 November 2026

How does BigInteger represent values, what makes its operations expensive, and when would you use it in a backend service?

BigInteger stores a sign and a magnitude, the magnitude being an int array of 32-bit words, so values can be any size and every operation returns a new immutable object. Its cost grows with the number of words: addition is linear, and multiplication starts with the schoolbook method and switches to Karatsuba and then Toom-Cook above size thresholds, which still grows faster than linearly. In a backend service I would use it for cryptography-related math, identifiers or checksums beyond 64 bits and exact combinatorics, prefer long with Math.*Exact whenever values fit, and bound the size of any BigInteger or BigDecimal built from untrusted input.

Background to this question

Most backend developers rarely touch BigInteger, which is why it is a good question: it shows whether we can reason about an unfamiliar class from first principles, and whether we know the one place where it becomes a security issue. Knowing how it works tells us when it is cheap, when it is expensive, and how an attacker can make it very expensive. In this answer, we will recap what BigInteger is for, look at how it represents values, see what makes its operations cost more than long arithmetic, list the realistic uses in a service, and finish with the denial of service risk and how to bound it.

1A Quick Recap: Integers Without a Size Limit

long is the largest primitive integer, with 64 bits and a maximum of about 9.2 x 10^18. Beyond that, Java offers java.math.BigInteger, an integer type with no fixed size. It can hold 2^1000 or the factorial of 1,000 exactly, and its operations never overflow; they simply produce a bigger number. BigDecimal, the exact decimal type, is built on it: a BigDecimal is a BigInteger unscaled value plus a scale.

2How BigInteger Represents a Value

Inside, a BigInteger has a signum, which is -1, 0 or 1, and a magnitude, an int[] holding the absolute value in base 2^32, with the most significant word first. So a number of n bits needs about n / 32 array elements. Zero has an empty magnitude, and the sign lives separately, so the magnitude is never stored in two's complement, although methods such as toByteArray and the bitwise operations behave as if it were.

Java
BigInteger big = BigInteger.TWO.pow(100);
System.out.println(big); // 1267650600228229401496703205376
System.out.println(big.bitLength()); // 101: needs 4 words of 32 bits internally
BigInteger next = big.add(BigInteger.ONE);
System.out.println(big == next); // false: add returned a new object
System.out.println(big.signum()); // 1
Step throughInside a BigInteger
  1. BigInteger objectheader plus fields such as signum, mag and cached values
  2. signum-1, 0 or 1; the sign is kept apart from the digits
  3. mag: int[]magnitude in base 2^32, most significant word first
  4. each operationallocates a new BigInteger and a new int[] for the result

4 layers, from the top down. Step through them one at a time.

Field names are implementation details of OpenJDK and may change between versions.

Every BigInteger is immutable, just like String. add, multiply, shiftLeft and every other operation allocate a new BigInteger with a new int array for the result. That is what makes BigInteger safe to share between threads, and it is also part of its cost.

3What Makes the Operations Expensive

A long addition is one processor instruction. A BigInteger addition is a loop over the words of both arrays with carries, plus allocating the result, so its cost grows linearly with the number of words. For numbers that fit in a long, that is already many times slower than primitive arithmetic, mostly because of the object allocation and the general-purpose code path.

Multiplication grows faster. The schoolbook method multiplies every word of one number by every word of the other, so its cost grows with the square of the size. For larger numbers, OpenJDK switches to the Karatsuba algorithm, which splits each number in half and needs three half-size multiplications instead of four, and for even larger numbers to Toom-Cook 3-way, which splits into thirds. The switch points are tuned thresholds of several dozen to a few hundred words (check your JDK version for exact values), and squaring has its own thresholds. These algorithms make big multiplications far faster than schoolbook, but cost still grows faster than the size of the input, and division, modPow and conversion to a decimal String are more expensive still.

Java
long a = 1_000_000_007L, b = 998_244_353L;
long p = Math.multiplyExact(a, b); // 998244359987710471: one instruction plus a check
BigInteger x = BigInteger.valueOf(a), y = BigInteger.valueOf(b);
BigInteger q = x.multiply(y); // same value, with allocation and loops
BigInteger huge = BigInteger.TEN.pow(1_000_000); // a million digits: noticeable CPU

The rule of thumb follows directly: if the values are known to fit in 64 bits, long with Math.*Exact is much cheaper and fails loudly on overflow. BigInteger is for values that genuinely need more.

4When a Backend Service Should Use It

There are a few realistic cases. The first is cryptography and related math, such as modular exponentiation with modPow, primality checks or working with RSA key components; in practice we use a crypto library, but BigInteger is the type underneath and the one we see in key specifications. The second is identifiers and hashes wider than 64 bits, such as a 128-bit value from a hash function or a UUID treated as a number, for example to convert it to a shorter base. The third is exact combinatorics, factorials or financial calculations whose intermediate results exceed long, and the fourth is checksums or protocols defined over large integers.

If an operation is only occasionally too large for long, Math.multiplyExact can try the fast path and fall back to BigInteger when it throws, which keeps the common case cheap.

5The Denial of Service Risk

Because cost grows with size, an attacker who controls the size can make a cheap request very expensive. The classic example is a number in scientific notation: the string 1e1000000000 is only twelve characters, and as a BigDecimal it is just a scale, but converting it to a BigInteger or a plain string means building a billion-digit number, which can consume huge amounts of memory and CPU. The same happens with untrusted exponents passed to pow, or with very long digit strings parsed into BigInteger.

Java
BigDecimal d = new BigDecimal("1e1000000000"); // cheap: unscaled value 1, scale -1000000000
// d.toBigInteger(); // tries to build a billion-digit number: CPU and memory blow-up
// d.toPlainString(); // the same problem
static BigDecimal parseAmount(String s) {
if (s.length() > 40) throw new IllegalArgumentException("amount too long");
BigDecimal v = new BigDecimal(s);
if (v.scale() > 10 || v.scale() < 0 || v.precision() > 30) throw new IllegalArgumentException("amount out of range");
return v;
}

The defence is to bound the input before doing arithmetic: limit the length of the string, the precision and scale of a BigDecimal, the bit length of a BigInteger and any exponent. JSON libraries have added limits of their own; for example, recent Jackson versions limit the length of numbers they will parse by default (check your version and its settings). Validation at the API boundary is still the clearest place to state what sizes the service accepts.

6Follow-up questions

Is BigInteger thread-safe?

Yes, because it is immutable. Every operation returns a new instance, so a BigInteger can be shared between threads without locking. The cost of that safety is an allocation for every intermediate result.

Why is converting a large BigInteger to a String slow?

Because the value is stored in base 2^32, and printing it in base 10 requires repeated division, which is one of the most expensive operations. OpenJDK uses a recursive divide-and-conquer approach for large values, but a number with millions of digits still takes noticeable time. That is one more reason to bound sizes from untrusted input.

7Conclusion

In this answer, we saw that BigInteger stores a separate sign and a magnitude in an int array of 32-bit words, so values have no size limit and every operation allocates a new immutable result. Addition costs grow linearly with the size, and multiplication moves from schoolbook to Karatsuba and Toom-Cook above thresholds but still grows faster than linearly. We use it for cryptographic math, identifiers and checksums wider than 64 bits and exact combinatorics, prefer long with Math.*Exact when values fit, and bound the size of anything built from untrusted input to avoid CPU and memory denial of service.

What to say in the interviewAbout 100 seconds aloud

Open with

BigInteger is an arbitrary-precision integer. Internally it keeps a signum, minus one, zero or one, and a magnitude as an int array in base 2 to the 32, most significant word first, so the size is limited only by memory.

Then, if they want more

It is immutable like String, which makes it thread-safe but means every operation allocates a new BigInteger and a new array. The cost grows with the number of words. Addition and subtraction are linear loops with carries.

Multiplication uses the schoolbook method for small values and switches to Karatsuba and then Toom-Cook 3-way above tuned thresholds, which is much faster for big numbers but still more than linear, and division, modPow and conversion to a decimal string are more expensive again.

So for anything that fits in 64 bits, long with Math.multiplyExact and the other exact methods is far cheaper, and I can fall back to BigInteger only when the exact method throws.

In a backend service I would use BigInteger for cryptography-related math, which is what crypto libraries use underneath, for 128-bit identifiers or hashes, for checksums beyond 64 bits and for exact combinatorics. The important risk is untrusted input.

A short string like 1e1000000000 parses cheaply into a BigDecimal, but converting it to a BigInteger or plain string builds a billion-digit number, which is a CPU and memory denial of service. So I bound the input length, precision, scale, bit length and exponents at the API boundary, and check the parser's own limits.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How does BigInteger represent values, what makes its operations expensive, and when...": https://scrivio-interview-library.netlify.app/java/types-and-values/44c78dd486/