Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

charutils
java
character
integer
communitycreator

What is CharUtils.toIntValue in Java?

abhilash

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.

How to import 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;

Syntax


public static int toIntValue(final char ch, final int defaultValue)

Parameters

  • final char ch: the character to be converted.
  • final int defaultValue: the default value to be returned if the character is not numeric

Return value

The method returns the integer value of the character passed, otherwise, it returns the default value.

Overloaded methods

public static int toIntValue(final char ch)

public static int toIntValue(final Character ch)

public static int toIntValue(final Character ch, final int defaultValue)

Code

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();
    }
}

Explanation

  • 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.

Output


The output of CharUtils.toIntValue() for the character '5' is 5
The output of CharUtils.toIntValue() for the character 'p' is -1

RELATED TAGS

charutils
java
character
integer
communitycreator
RELATED COURSES

View all Courses

Keep Exploring