Convert String to BigInteger in Java [3 ways]

In this post, I will be sharing how to convert String to BigInteger in Java. According to Oracle docs, the BigInteger class is commonly used for working with large numerical values. There are three ways to achieve our goal:

1. Using String constructor

2. Using BigDecimal class toBigInteger() method

3. Using byte[] constructor

Read Also: Convert BigInteger to BigDecimal in Java

Let's dive deep into the topic:

Convert String to BigInteger in Java

1. Using String constructor


It is easy to convert String to BigInteger using the BigInteger class String constructor. The syntax is given below:

 BigInteger(String val)


The above constructor helps in converting String representation to BigInteger. Let's find out with the help of an example:

 import java.math.BigInteger;
public class StringToBigInteger {
    public static void main(String args[]) {
        String str1 = "25";
        BigInteger num = new BigInteger(str1);
        System.out.println("Converted String to BigInteger: " + num);
    }
}


Output:
Converted String to BigInteger: 25


2. Using BigDecimal class toBigInteger() method


It is easy to convert String to BigInteger using BigDecimal class toBigInteger() method as shown below:

 import java.math.BigInteger;
import java.math.BigDecimal;
public class StringToBigInteger2 {
    public static void main(String args[]) {
        String str1 = "1234567";
        BigInteger num = new BigDecimal(str1).toBigInteger();
        System.out.println("Converted String to BigInteger using BigDecimal: " + num);
    }
}


Output:
Converted String to BigInteger using BigDecimal: 1234567


3. Using byte[] constructor


It is easy to convert String to BigInteger using BigInteger class byte[] constructor. The syntax is given below:

 BigInteger(byte[] val)


First we need to convert String into byte[] using getBytes() method. Then we can pass the byte[] to the BigInteger constructor and get the desired output as shown below:
 import java.math.BigInteger;
public class StringToBigInteger3 {
    public static void main(String args[]) {
        String str1 = "105";
        byte[] arr = str1.getBytes();
        BigInteger num = new BigInteger(arr);
        System.out.println("Converted String to BigInteger using byte[]: " + new String(num.toByteArray()));
    }
}


Output:
Converted String to BigInteger using byte[]: 105


That's all for today. Please mention in the comments in case you have any questions related to how to convert String to BigInteger in Java.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry