What is NumberUtils.createLong() in Java?

createLong() is a staticthe methods in Java that can be called without creating an object of the class. method of the NumberUtils class that is used to convert a string to a Long datatype. If the string cannot be converted to a Long 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 Long createLong(final String str)

Parameters

  • final String str: The string to convert.

Return value

This method returns the converted Long value.

Code

The code below shows how the NumberUtils.createLong() method works in Java.

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

Output

The output of the code will be as follows:


NumberUtils.createLong(234323) = 234323
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.Long.parseLong(Long.java:692)
	at java.base/java.lang.Long.valueOf(Long.java:1117)
	at java.base/java.lang.Long.decode(Long.java:1268)
	at org.apache.commons.lang3.math.NumberUtils.createLong(NumberUtils.java:948)
	at Main.main(Main.java:13)

Explanation

Example 1

  • string value = 234323

The method returns 234323 as the conversion is successful.

Example 2

  • string value = 234323wrf

The method throws NumberFormatException as the conversion is unsuccessful.

Free Resources