toIntValue
is a static method of CharUtils
class that is used to convert the given character to an integer. If the input character is null
or not an integer, then the default value passed as an argument will be returned.
CharUtils
CharUtils
is defined in the Apache Commons Lang
package. Apache Commons Lang
can be added 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.
We can import the CharUtils
class as follows.
import org.apache.commons.lang3.CharUtils;
public static int toIntValue(final char ch, final int defaultValue)
final char ch
: the character to be converted.final int defaultValue
: the default value to be returned if the character is not numericThe method returns the integer value of the character passed, otherwise, it returns the default value.
public static int toIntValue(final char ch)
public static int toIntValue(final Character ch)
public static int toIntValue(final Character ch, final int defaultValue)
import org.apache.commons.lang3.CharUtils; public class Main { public static void main(String[] args) { char c1 = '5'; int defaultValue = -1; System.out.printf("The output of CharUtils.toIntValue() for the character '%s' is %s", c1, CharUtils.toIntValue(c1, defaultValue)); System.out.println(); c1 = 'p'; System.out.printf("The output of CharUtils.toIntValue() for the character '%s' is %s", c1, CharUtils.toIntValue(c1, defaultValue)); System.out.println(); } }
character - '5'
defaultValue = -1
The method returns 5
as the character is a numeric value.
character - 'p'
defaultValue = -1
The method returns -1
as the character is not a numeric value and returns the default value passed.
The output of CharUtils.toIntValue() for the character '5' is 5
The output of CharUtils.toIntValue() for the character 'p' is -1
RELATED TAGS
CONTRIBUTOR
View all Courses