createLong()
is a 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.
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 Long createLong(final String str)
final String str
: The string to convert.This method returns the converted Long
value.
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 1String valueToConvert = "234323";System.out.printf("NumberUtils.createLong(%s) = %s", valueToConvert, NumberUtils.createLong(valueToConvert));System.out.println();// Example 2valueToConvert = "234323wrf";System.out.printf("NumberUtils.createLong(%s) = %s", valueToConvert, NumberUtils.createLong(valueToConvert));System.out.println();}}
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)
string value = 234323
The method returns 234323
as the conversion is successful.
string value = 234323wrf
The method throws NumberFormatException
as the conversion is unsuccessful.