Way2Java

toCharArray() String Example

java.lang.String class comes with toCharArray() String method to convert string to a character array.

The signature is given of toCharArray() String as defined in Java API.

In the following toCharArray() String is used to get a char array out of string.
public class StringMethodDemo
{
 public static void main(String args[])
 {
  String str1 = "ABCDEFGHI";    		

  char carray[] = str1.toCharArray();

  System.out.println("String: " + str1);
  System.out.println("Length of string: " + str1.length());
  System.out.println("Length of array returned: " + carray.length);

  System.out.println("\nArray characters:");
  for(char temp : carray)
  {
    System.out.print(temp + ", ");
  }
 }
}



Output screen of toCharArray() String Example

As each character of string becomes an element of the array, the length of both is same. Observe screenshot.

A similar method exists in String class doing the same job but with a small difference – getChars().

Pass your comments and suggestions on this tutorial "toCharArray() String Example".