Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

charutils
java
communitycreator

What is CharUtils.toString in Java?

abhilash

The toString method is a static method of the CharUtils class that converts the input character of primitive type (char) or the object type (Character) to the equivalent string.

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 String toString(char ch)

Parameters

  • ch: the character to be converted into a string.

Return value

The function returns a string that contains the specified character.

Code

import org.apache.commons.lang3.CharUtils;

public class Main {

    private static void check(char ch){
        if(CharUtils.toString(ch) instanceof String){
            System.out.println("The method CharUtils.toString() returned a string for the character " + ch);
        }else {
            System.out.println("The method CharUtils.toString() did not return a string for the character " + ch);
        }
    }

    public static void main(String[] args) {
        check('t');
        check('4');
        check('~');
    }
}

Expected output

The method CharUtils.toString() returned a string for the character t
The method CharUtils.toString() returned a string for the character 4
The method CharUtils.toString() returned a string for the character ~

Explanation

In the code above, the check method verifies whether the return value of the CharUtils.toString() method is of the String type or not using the instanceof operator.

Different character inputs are passed to the method to verify the behavior of the CharUtils.toString() method.

RELATED TAGS

charutils
java
communitycreator
RELATED COURSES

View all Courses

Keep Exploring