Codectionary / Developer documentation / Java

BigInteger Arithmetic

BigInteger stores integers beyond the range of long. Its immutable arithmetic methods return new values and avoid primitive integer overflow. Save as Main.java and run with a Java 17+ JDK: java Main.java.

Syntax

BigInteger.valueOf(value).pow(exponent); a.gcd(b)

Examples

BigInteger Arithmetic

Save as Main.java and run with a Java 17+ JDK: java Main.java.

import java.math.BigInteger;

public class Main {
  public static void main(String[] args) throws Exception {
    BigInteger value = BigInteger.valueOf(2).pow(100);
    System.out.println(value);
    System.out.println(BigInteger.valueOf(84).gcd(BigInteger.valueOf(30)));
  }
}
  1. Expected output: 1267650600228229401496703205376 6
  2. The power exceeds a 64-bit integer. gcd computes the greatest common divisor without converting back to a primitive.

Best practices

  • Use intValueExact or longValueExact when narrowing must reject overflow.
  • Bound input sizes for computations driven by untrusted input.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading