toInt()
is a NumberUtils
class that is used to convert the given string to an integer
value. One variant of the method accepts a default value that is returned if the conversion fails.
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 int toInt(final String str, final int defaultValue)
final String str
: The string to convert.final int defaultValue
: The default value to return.This method returns an int
value else the default value if the conversion fails.
public static int toInt(final String str)
import org.apache.commons.lang3.math.NumberUtils;public class Main{public static void main(String[] args){// Example 1String stringToConvert = "23";int defaultValue = 24;System.out.printf("The output of the method NumberUtils.toInt(%s, %s) is %s", stringToConvert, defaultValue, NumberUtils.toInt(stringToConvert, defaultValue));System.out.println();// Example 2stringToConvert = "233sdf";defaultValue = 24;System.out.printf("The output of the method NumberUtils.toInt(%s, %s) is %s", stringToConvert, defaultValue, NumberUtils.toInt(stringToConvert, defaultValue));System.out.println();}}
stringToConvert = "23"
defaultValue = 24
The method returns 23
as the conversion is successful.
stringToConvert = "233sdf"
defaultValue = 24
The method returns 24
as the conversion is unsuccessful.
The output of the code will be as follows:
The output of the method NumberUtils.toInt(23, 24) is 23
The output of the method NumberUtils.toInt(233sdf, 24) is 24
Free Resources