String to Char Array Java Tutorial
--
In this article, we’ll look at how to convert a string to an array of characters in Java. I’ll also briefly explain to you what strings, characters, and arrays are.
What is a Character in Java?
Characters are primitive datatypes. A character is a single character enclosed inside single quotation marks. It can be a letter, a digit, a punctuation mark, a space or something similar. For example:
char firstVowel = 'a';
What is a String in Java?
Strings are objects (reference type). A string is made up of a string of characters. It’s anything inside double quotation marks. For example:
String vowels = "aeiou";
What is an Array in Java?
Arrays are fundamental data structures that can store a fixed number of elements of the same data type in Java. For example, let’s declare an array of characters:
char[] vowelArray = {'a', 'e', 'i', 'o', 'u'};
Now, we have a basic understanding of what strings, characters, and arrays are.
Let’s Convert a String to a Character Array
1. Use toCharArray() Instance Method
toCharArray()
is an instance method of the String
class. It returns a new character array based on the current string object.
Let’s check out an example:
// define a string
String vowels = "aeiou";// create an array of characters
char[] vowelArray = vowels.toCharArray();// print vowelArray
System.out.println(Arrays.toString(vowelArray));
Output: [a, e, i, o, u]
When we convert a string to an array of characters, the length remains the same. Let’s check the length of both vowels
and vowelArray
:
System.out.println("Length of \'vowels\' is " + vowels.length());
System.out.println("Length of \'vowelArray\' is " + vowelArray.length);
Output:
Length of 'vowels' is 5
Length of 'vowelArray' is 5