String toCharArray()

In java, there are a number of methods in String class that are used to perform different operations. In this post we will see tochararray() java and see how to convert string to char array.

What is string toCharArray() method

In java string toCharArray() method is used to convert string to char array. It is the easiest way to convert a java string to char array, the toCharArray() method creates a new character array with the same length as the length of the string. When it creates a new char array, the original string is left unchanged.

String.toCharArray();
string tochararray()

public: It is an access modifier that defines the access of method. This method is public so it can access everywhere.
char[]: It returns an array of char type.
no parameter: It doesn’t take any parameter.

class ExampleOfSplit
 {  
		 public static void main(String args[])
		 {  
			String str1 = "A Java learning JAVAGOAL.COM";  
			char[] result = str1.toCharArray();
			System.out.println("Length of String: "+str1.length());
			System.out.println("Length of Array: "+result.length);
			
			for(char s : result)
	        	System.out.println(s);
		 }  
}  

Output: Length of String: 28
Length of Array: 28
A

J
a
v
a

l
e
a
r
n
i
n
g

J
A
V
A
G
O
A
L
.
C
O
M

In the above example, we can see we are using string tochararray() to convert string to array. The string is broken down into an array of characters, the length of the array equals to the length of the string. The string broke down into characters and each character is assigned to a particular index. The first character assigned on the first index of the character array and last character assigned to the last index.

Leave a Comment