java.lang.String toCharArray()

Description :

This java tutorial shows how to use the toCharArray() method of String class of java.lang package. This method returns a character array which corresponds to the character elements of our String.

Method Syntax :

public char[] toCharArray()

Parameter Input :

DataType Parameter Description
N/A N/A N/A

Method Returns :

This String toCharArray() method returns an array of characters which corresponds to the composition of our String in terms of characters equivalent.

Compatibility Version :

Since the beginning

Exception :

NullPointerException

This can only be encountered if the String is null

Discussion :

The method toCharArray() is simply to converts our String object into array of characters. This is necessary especially if we needed to pass to a character array instead of String to java methods and API.

Supposed that we have the following string “Java String example”. If we want to convert it into a character array we would having the following:

String sampleString = "Java String Example";
char [] list = sampleString.toCharArray();

It’s pretty straightforward way to convert to character array. The string is broken down into set of characters, the first character to be assign on the first index of the character array which is index 0. Always remember that in dealing with arrays the general rule is first index would be 0;

As exercise, what do you think would be the contents of list[1] coming from the code snippet above? If you answer “J” that is incorrect. As i have said the index of an array begin at 0, so that would mean list[1] = “a”.

Java Code Example :

This example source code demonstrates the use of toCharArray() method of String class to converts a String object into character array. We have use the Arrays.toString method to print the value of our character array.

package com.javatutorialhq.java.tutorial.string;

/*
 * This is a java example source code
 * to convert a String to character array
 * simply to demostrate the use of toCharArray()
 * of String class
 */

import java.util.Arrays;

public class StringToCharArrayDemo {

	public static void main(String[] args) {
		// String declaration
		String stringValue = "This is a sample string";
		// Convert String to char array
		char[] charArray = stringValue.toCharArray();
		// array printing of character array
		System.out.println(Arrays.toString(charArray));
	}

}

Sample Output :

Running the toCharArray() method example source code of String class will give you the following output

string tochararray method example

string tochararray method example

Exception Scenario :

Exception in thread "main" java.lang.NullPointerException
	at com.teknoscope.java.tutorial.string.StringToCharArrayDemo.main(StringToCharArrayDemo.java:16)

Suggested Reading List :

References :