What is NumberUtils.createInteger in Java?

createInteger() 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 an Integer datatype.

If the string cannot be converted to an integer value, then NumberFormatException will be thrown by the method.

This method can also cater to strings of hexadecimal and octal notation.

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 Integer createInteger( String str)

Parameters

  • str: The string to convert to an integer.

Return value

This method returns the converted integer value.

If the string passed as an argument is null, then null is returned by the method.

Code

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

Output

The output of the code is as follows:


NumberUtils.createInteger(234323232) = 234323232

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.lang.Integer.valueOf(Integer.java:957)
	at java.base/java.lang.Integer.decode(Integer.java:1436)
	at org.apache.commons.lang3.math.NumberUtils.createInteger(NumberUtils.java:930)
	at Main.main(Main.java:13)

Explanation

Example 1

  • valueToConvert = "234323232"

The method returns 234323232 since the conversion is successful.

Example 2

  • valueToConvert = "234323wrf"

The method throws NumberFormatException since the letters cannot be converted to an integral value.

Free Resources

Attributions:
  1. undefined by undefined