Java String toCharArray() Example | Java toCharArray() Function

Java String toCharArray() is an inbuilt method that is used to return a sequence of into an array of characters. The length of the array is equal to the length of the string. The java string toCharArray() method converts the given string into a sequence of characters. The returned array length is equal to the length of the string.

Java String toCharArray()

The method returns an Array of chars after converting a String into a sequence of characters. The returned array length is equal to the length of the String, and the sequence of chars in Array matches the sequence of characters in the String.


public char[] toCharArray()

See the following code example.

class Chararr {
	public static void main(String args[]) {
		// initializing the string
		String str = "Appdividend";
		// converting the string into character array
		char[] ch = str.toCharArray();
		// printing array values
		for (int i = 0; i < ch.length; i++) {
			System.out.print(ch[i] + " ");

See the output.

Java toCharArray() Function

Convert String to char in Java

The string class has three methods related to char. Let’s look at them before we look at a java program to convert string to char array.

char[] toCharArray()

The method converts the string to a character array. The char array size is the same as the length of the string.

char charAt(int index)

This method returns the character at a specific index of string. This method throws StringIndexOutOfBoundsException if the index argument value is negative or greater than the length of the string.

getChars(int srcBegin, int srcEnd, char dst[], int dstBegin)

This is a beneficial method when you want to convert part of the string to a character array. First, two parameters define the start and end index of the string; the last character to be copied is at index srcEnd-1. 

The characters are copied into the char array starting at index dstBegin and ending at dstBegin + (srcEnd-srcBegin) – 1.

See the following program.

class Chararr {
	public static void main(String[] args) {
		String str = "Jesse Pinkman";
		//string to char array
		char[] chars = str.toCharArray();
		//char at specific index
		char c = str.charAt(2);
		//Copy string characters to char array
		char[] chars1 = new char[7];
		str.getChars(0, 7, chars1, 0);

See the output.

➜  java javac
➜  java java Chararr
Jesse P
➜  java

Finally, Java String toCharArray() Example tutorial is over.

Recommended Posts

Java String indexOf() Example

Java String compareTo Example

Java String valueOf() Example

How to find string length In Java

Java Trim String Example

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.