What is NumberUtils.createBigInteger in Java?

createBigInteger() is a staticthe methods in Java that can be called without creating an object of the class. method of the 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.

How to import 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;

Syntax


public static BigInteger createBigInteger(String str)

Parameters

  • str: The string to convert to a BigInteger value.

Return value

This method returns the converted BigInteger value.

If a null string is passed to the method, null is returned.

Code

import org.apache.commons.lang3.math.NumberUtils;
public class Main{
public static void main(String[] args){
// Example 1
String valueToConvert = "234323232232";
System.out.printf("NumberUtils.createBigInteger(%s) = %s", valueToConvert, NumberUtils.createBigInteger(valueToConvert));
System.out.println();
// Example 2
valueToConvert = "234323wrf";
System.out.printf("NumberUtils.createBigInteger(%s) = %s", valueToConvert, NumberUtils.createBigInteger(valueToConvert));
System.out.println();
}
}

Output

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)

Explanation

Example 1

  • valueToConvert = "234323232232"

The method returns 234323232232 since the conversion is successful.

Example 2

  • valueToConvert = "234323wrf"

The method throws NumberFormatException as the conversion is unsuccessful.

Free Resources

Attributions:
  1. undefined by undefined