Java String toCharArray() Method

Java String toCharArray() Method | The method toCharArray() converts the given string to the sequence of characters. This method takes any parameter and returns the sequence of characters in the array format.

The syntax of the toCharArray() is as follows:- public char[ ] toCharArray()
Parameters:- no parameters accepted.
Return type:- character.
Returns:- sequence of character.

Java String toCharArray() Example

Now, let us see some examples of the Java String toCharArray() method. We will take a string and call the toCharArray() method to get the array of characters from the string. And later we will display the array of characters using the Arrays.toString() method.

import java.util.Arrays;

public class Main {
   public static void main(String args[]) {
      String string = "Java Programming Language";
      char[] charArray = string.toCharArray();
      System.out.println(Arrays.toString(charArray));
   }
}

Output:-

[J, a, v, a, , P, r, o, g, r, a, m, m, i, n, g, , L, a, n, g, u, a, g, e]

In the previous example, we have displayed the array of characters using the Arrays.toString() method but we can also use the normal for loop or for-each loop to display the array of characters. See:- Different ways to print array. Let us see another example of the String.toCharArray() in Java.

public class Main {
   public static void main(String args[]) {
      String string = "Know Program";
      char[] charArray = string.toCharArray();
      for (int i = 0; i < charArray.length; i++) {
         System.out.print(charArray[i] + ", ");
      }
   }
}

Output:-

K, n, o, w, , P, r, o, g, r, a, m,

Also see:- How to convert string to char array using the native method, Java program to convert char array to string.

Java toCharArray() Example

public class Main {
   public static void main(String[] args) {
      String string = "Welcome to Know Program";
      char[] charArray = string.toCharArray();
      int length = charArray.length;
      System.out.println("Char Array length: " + length);
      System.out.println("Char Array elements: ");
      for (char ch : charArray) {
         System.out.print(ch + " ");
      }
   }
}

Output:-

Char Array length: 23
Char Array elements:
W e l c o m e t o K n o w P r o g r a m

public class Main {
   public static void main(String args[]) {
      String string = "Where there is a will there is a way";
      System.out.println("The string array: ");
      System.out.println(string.toCharArray());
   }
}

Output:-

The string array:
Where there is a will there is a way

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *