Java String toCharArray() is an inbuilt method that is used to return a sequence of into an array of characters. The length of the array is equal to the length of the string. The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string.
Java String toCharArray()
The method returns an Array of chars after converting a String into a sequence of characters. The returned array length is equal to the length of the String, and the sequence of chars in Array matches the sequence of characters in the String.
Syntax
public char[] toCharArray()
See the following code example.
class Chararr { public static void main(String args[]) { // initializing the string String str = "Appdividend"; // converting the string into character array char[] ch = str.toCharArray(); // printing array values for (int i = 0; i < ch.length; i++) { System.out.print(ch[i] + " "); } System.out.println("\n"); } }
See the output.
Convert String to char in Java
The string class has three methods related to char. Let’s look at them before we look at a java program to convert string to char array.
char[] toCharArray()
The method converts the string to a character array. The char array size is the same as the length of the string.
char charAt(int index)
This method returns the character at a specific index of string. This method throws StringIndexOutOfBoundsException if the index argument value is negative or greater than the length of the string.
getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)
This is a beneficial method when you want to convert part of the string to a character array. First, two parameters define the start and end index of the string; the last character to be copied is at index srcEnd-1.
The characters are copied into the char array starting at index dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.
See the following program.
class Chararr { public static void main(String[] args) { String str = "Jesse Pinkman"; //string to char array char[] chars = str.toCharArray(); System.out.println(chars.length); //char at specific index char c = str.charAt(2); System.out.println(c); //Copy string characters to char array char[] chars1 = new char[7]; str.getChars(0, 7, chars1, 0); System.out.println(chars1); } }
See the output.
➜ java javac Chararr.java ➜ java java Chararr 13 s Jesse P ➜ java
Finally, Java String toCharArray() Example tutorial is over.