Convert String to char Array in Java
Problem
A Java String is immutable, so its characters can't be changed in place; copying them into a char array gives you a mutable sequence you can edit freely.
Given a word, convert it to an array of characters, change the array, and show that the original string is unaffected.
Java Program
import java.util.Arrays;
public class StringToCharArray {
public static void main(String[] args) {
String word = "Coffee";
char[] letters = word.toCharArray(); // a fresh copy, independent of the string
System.out.println(Arrays.toString(letters));
letters[0] = 'c'; // editing the array leaves the original string untouched
System.out.println("Array now: " + new String(letters));
System.out.println("String still: " + word);
}
}Output
Core Logic
toCharArray returns a brand-new array filled with the string's characters, so changes to the array never reach the string.
- 1
word.toCharArray()creates achar[]of length 6 holding each character. - 2
Arrays.toString(letters)prints the array in a readable bracketed form. - 3
letters[0] = 'c'changes only the array's first element. - 4
new String(letters)turns the edited array back into a string, whilewordstill prints as before.
coffee but word is still Coffee.Key Point: Converting to a char array is the standard first step for in-place string algorithms such as reversing with two pointers or sorting the letters of a word.
Why: Every one of the n characters is copied into a new array of the same length.
Key Concepts
Approach 2: Manual Copy with charAt()
import java.util.Arrays;
public class StringToCharArrayManual {
public static void main(String[] args) {
String word = "Coffee";
char[] letters = new char[word.length()];
for (int i = 0; i < word.length(); i++) {
letters[i] = word.charAt(i); // copy one character at a time
}
System.out.println(Arrays.toString(letters));
}
}
Output
Core Logic
The same array can be filled by hand: allocate it to the string's length and copy characters one index at a time.
- 1
new char[word.length()]creates an empty array of the right size. - 2The loop runs
ifrom 0 tolength - 1. - 3
letters[i] = word.charAt(i)copies each character to the same position.
"Coffee" is 'f', so letters[2] becomes 'f'.Key Point: This version is useful when you only want part of the string, or want to transform characters as you copy — otherwise toCharArray is simpler.
Why: One pass copies n characters into an n-length array.
Key Concepts
Interview Questions
Does changing the char array change the original string?
No. toCharArray() returns a new copy, so edits to the array never affect the immutable String.
How do you turn a char array back into a string?
Use new String(chars) or String.valueOf(chars). Calling chars.toString() prints the array's type and hash code, not its contents.