Java convert BigInteger to int
Tags: BigInteger BigInteger intValueExact BigInteger intValue int
In this Java core tutorial we learn how to use the java.math.BigInteger.intValueExact() and java.math.BigInteger.intValue() method to convert a BigInteger object into an integer value.
How to convert BigInteger object to int value
To convert a BigInteger value into int value we can use the method java.math.BigInteger.intValueExact(). This method also checks the value of BigInteger if it is out of range of integer then an ArithmeticException is thrown.
ConvertBigIntegerToIntExample1.java
import java.math.BigInteger;
public class ConvertBigIntegerToIntExample1 {
public static void main(String... args) {
BigInteger value = new BigInteger("78999");
int intValue = value.intValueExact();
System.out.println("BigInteger value: " + value);
System.out.println("int value: " + intValue);
}
}
BigInteger value: 78999
int value: 78999
We also can use the java.math.BigInteger.intValue() method which casts the BigInteger value to int.
ConvertBigIntegerToIntExample2.java
import java.math.BigInteger;
public class ConvertBigIntegerToIntExample2 {
public static void main(String... args) {
BigInteger value = new BigInteger("65999");
int intValue = value.intValue();
System.out.println("BigInteger value: " + value);
System.out.println("int value: " + intValue);
}
}
BigInteger value: 65999
int value: 65999
Happy Coding 😊
Related Articles
Java convert int to BigInteger
Java convert BigInteger to String
Java convert BigInteger to short
Java convert BigInteger to long
Java convert BigInteger to float