Java: String toCharArray() method

In this article, we will discuss how to convert String into char[] array using String’s toCharArray() method

toCharArray() method: This String method is used to convert any given string into char[] array

 

Method Signature:

public char[] toCharArray();

 

Returns:

  • New char[] array equivalent to string’s length
  • Whose contents are initialized to contain the character sequence represented by the invoking string

 

Examples on toCharArray() method:

To create equivalent char[] array for the invoking string

StringToCharArrayMethod.java

package in.bench.resources.string.methods;

public class StringToCharArrayMethod {

	public static void main(String[] args) {

		// sample string
		String url = "JavaWorld";

		// convert string into char[] array
		char[] chArray = url.toCharArray();

		// iterate using for-loop & store into char[] array
		for(char ch : chArray) {
			System.out.println(ch);
		}
	}
}

Output:

J
a
v
a
W
o
r
l
d

 

Hope, you found this article very helpful. If you have any suggestions or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here.

 

References:

https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html
https://docs.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
https://docs.oracle.com/javase/tutorial/java/data/strings.html
https://docs.oracle.com/javase/6/docs/api/java/lang/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/7/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/8/docs/api/java/lang/class-use/String.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html
https://docs.oracle.com/javase/6/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html
https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html

 

Happy Coding !!
Happy Learning !!

Java: String toLowerCase() method
Java: String substring() method