1. Using BigInteger class valueOf() method
2. Using BigDecimal class toBigInteger() method
Read Also: Convert String to BigInteger in Java
Let's dive deep into the topic:
Convert Integer to BigInteger in Java
1. Using BigInteger class valueOf() method
You can easily use BigInteger class valueOf() method to convert Integer to BigInteger in Java. The syntax is given below:
public static BigInteger valueOf(long val)
Below is the complete example to convert Integer and primitive int to BigInteger in Java using the valueOf() method:
import java.math.BigInteger;
public class IntegertoBigInteger {
public static void main(String args[]) {
// Converting int to BigInteger
System.out.println("Converting int to BigInteger");
int num = 123456;
BigInteger bi = BigInteger.valueOf(num);
System.out.println(bi);
// Converting Integer to BigInteger
System.out.println("Converting Integer to BigInteger");
Integer num2 = 12345678;
BigInteger bi2 = BigInteger.valueOf(num2);
System.out.println(bi2);
}
}
Output:
Converting int to BigInteger
123456
Converting Integer to BigInteger
12345678
2. Using BigDecimal class toBigInteger() method
You can simply use BigDecimal class toBigInteger() method to convert Integer and primitive int to BigInteger in Java. First, we need to convert Integer and primitive int to BigDecimal before using the toBigInteger() method as shown below in the example:
import java.math.BigInteger;
import java.math.BigDecimal;
public class IntegertoBigInteger2 {
public static void main(String args[]) {
// Converting int to BigInteger using BigDecimal class
System.out.println("Converting int to BigInteger");
int num = 234567;
BigInteger bi3 = BigDecimal.valueOf(num).toBigInteger();
System.out.println(bi3);
// Converting Integer to BigInteger using BigDecimal class
System.out.println("Converting Integer to BigInteger");
Integer num2 = 23456789;
BigInteger bi4 = BigDecimal.valueOf(num2).toBigInteger();
System.out.println(bi4);
}
}
Output:
Converting int to BigInteger
234567
Converting Integer to BigInteger
23456789
That's all for today, please mention in the comments in case you have any questions related to how to convert Integer to BigInteger in Java.