createBigInteger()
is a NumberUtils
class which is used to convert a string to a BigInteger
datatype.
If the string cannot be converted to a big integer value, then NumberFormatException
will be thrown by the method.
NumberUtils
The definition of NumberUtils
can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml
file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the NumberUtils
class as follows:
import org.apache.commons.lang3.math.NumberUtils;
public static BigInteger createBigInteger(String str)
str
: The string to convert to a BigInteger
value.This method returns the converted BigInteger
value.
If a null
string is passed to the method, null
is returned.
import org.apache.commons.lang3.math.NumberUtils;public class Main{public static void main(String[] args){// Example 1String valueToConvert = "234323232232";System.out.printf("NumberUtils.createBigInteger(%s) = %s", valueToConvert, NumberUtils.createBigInteger(valueToConvert));System.out.println();// Example 2valueToConvert = "234323wrf";System.out.printf("NumberUtils.createBigInteger(%s) = %s", valueToConvert, NumberUtils.createBigInteger(valueToConvert));System.out.println();}}
The output of the code will be as follows:
NumberUtils.createBigInteger(234323232232) = 234323232232
Exception in thread "main" java.lang.NumberFormatException: For input string: "234323wrf"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.math.BigInteger.<init>(BigInteger.java:534)
at org.apache.commons.lang3.math.NumberUtils.createBigInteger(NumberUtils.java:983)
at Main.main(Main.java:13)
valueToConvert
= "234323232232"
The method returns 234323232232
since the conversion is successful.
valueToConvert
= "234323wrf"
The method throws NumberFormatException
as the conversion is unsuccessful.
Free Resources