What is CharSequenceUtils.toCharArray in Java?
toCharArray() is a CharSequenceUtils class that is used to convert the given character sequence of CharSequence type to a character array.
How to import CharSequenceUtils
The definition of CharSequenceUtils 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 CharSequenceUtils class as follows.
import org.apache.commons.lang3.CharSequenceUtils;
Syntax
public static char[] toCharArray(final CharSequence source)
Parameters
source: The character sequence to convert to an array.
Return value
This method returns the equivalent character array.
Code
import org.apache.commons.lang3.CharSequenceUtils;import java.util.Arrays;public class Main{public static void main(String[] args){String characterSequence = "hello-educative";System.out.printf("The output of CharSequenceUtils.toCharArray() for the string - '%s' is '%s'", characterSequence, Arrays.toString(CharSequenceUtils.toCharArray(characterSequence)));System.out.println();characterSequence = null;System.out.printf("The output of CharSequenceUtils.toCharArray() for the string - '%s' is '%s'", characterSequence, Arrays.toString(CharSequenceUtils.toCharArray(characterSequence)));System.out.println();}}
Output
The output of CharSequenceUtils.toCharArray() for the string - 'hello-educative' is '[h, e, l, l, o, -, e, d, u, c, a, t, i, v, e]'
The output of CharSequenceUtils.toCharArray() for the string - 'null' is '[]'
Explanation
Example 1
characterSequence = "hello-educative"
The method returns [h, e, l, l, o, -, e, d, u, c, a, t, i, v, e] where the input string is converted to an array.
Example 2
characterSequence = null
The method returns [] because the input string is null.