Home >>Java String Methods >Java String toCharArray() Method

Java String toCharArray() Method

Java String toCharArray() Method

Java toCharArray() method in Java String is used to converts this string to array of characters. It returns a newly generated character sequence, its length is identical to that string and it initializes its contents with the characters of that string.

Internal implementation

public char[] toCharArray() 
{  
      char result[] = new char[value.length];  
      System.arraycopy(value, 0, result, 0, value.length);  
      return result;  
  }  

Syntax

public char[] toCharArray()

Returns

It is used to returns the character array

Java String toCharArray() Method Example 1


public class MyClass
{  
public static void main(String args[])
{  
String n1="Phptpoint";  
char[] Name=n1.toCharArray();  
for(int i=0;i<Name.length;i++)
{  
System.out.print(Name[i]);  
}  
}
}  

Output:
Phptpoint

Java String toCharArray() Method Example 2


public class MyClass 
{  
    public static void main(String[] args) 
	{  
        String x1 = "Welcome to Phptpoint";  
        char[] y = x1.toCharArray();  
        int len = y.length;  
        System.out.println("Char Array length: " + len);  
        System.out.println("Char Array elements: ");  
        for (int i = 0; i < len; i++) 
		{  
            System.out.println(y[i]);  
        }  
    }  
}  

Output:
Char Array length: 20
Char Array elements:
W
e
l
c
o
m
e
t
o
P
h
p
t
p
o
i
n
t

No Sidebar ads