.toCharArray()
Published Feb 28, 2023
Contribute to Docs
The method .toCharArray()
returns a new character array from the given string. The length of the array is equal to the length of the original string.
Syntax
string.toCharArray()
string
is the string to be transformed to a new array of characters.- This method doesn’t take any parameters.
Example
The example below uses the .toCharArray()
method to create a new array, uses a loop to iterate through the array, and prints each character:
// Example.javaclass Example {public static void main(String[] args) {String salutation = "Hello Codecademy!";char[] textArray = salutation.toCharArray();for (int i = 0; i < textArray.length; i++) {System.out.println(textArray[i]);}}}
This will produce the following output:
HelloCodecademy!
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Java on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn Java
Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.Beginner Friendly16 hours