Java
Programming
Loops
For-Each Loop
String Manipulation

How do I apply the for-each loop to every character in a String?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

In Java, you cannot use the enhanced for-each loop directly on a String, because String is not an Iterable of characters. The usual fix is to convert the string to a character array first, or to iterate by index. Which one you choose depends on whether you care about raw UTF-16 code units or full Unicode code points.

The Standard Approach: toCharArray()

For ordinary character-by-character processing, the most direct option is converting the string to a char[] and then using a for-each loop.

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "hello";
4
5        for (char ch : text.toCharArray()) {
6            System.out.println(ch);
7        }
8    }
9}

This works because arrays support the enhanced for syntax, while String itself does not.

Why for-each Does Not Work on String

The enhanced for loop in Java works on:

  • arrays
  • objects that implement Iterable

String provides methods such as charAt and codePoints, but it does not implement a character-iterable interface directly. So code like this does not compile:

java
for (char ch : text) {
    System.out.println(ch);
}

That is why developers usually switch to toCharArray() or an index-based loop.

Index-Based Iteration

If you need the character position as well as the character itself, iterate by index.

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "world";
4
5        for (int i = 0; i < text.length(); i++) {
6            char ch = text.charAt(i);
7            System.out.println(i + ": " + ch);
8        }
9    }
10}

This is often the better choice when position matters or when you want to avoid creating a temporary array.

Unicode Matters More Than Many People Expect

A Java char is a UTF-16 code unit, not always a full user-visible character. Some Unicode characters, such as many emoji, use two char values as a surrogate pair.

If you need true Unicode character iteration, use code points instead of char.

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "A🙂B";
4
5        text.codePoints().forEach(cp ->
6            System.out.println(new String(Character.toChars(cp)))
7        );
8    }
9}

This is the correct approach when your application processes modern Unicode text rather than simple ASCII-like input.

Converting Code Points to a Loop-Friendly Form

If you specifically want a loop structure resembling for-each, you can convert code points to an array first.

java
1public class Main {
2    public static void main(String[] args) {
3        String text = "A🙂B";
4
5        for (int cp : text.codePoints().toArray()) {
6            System.out.println(new String(Character.toChars(cp)));
7        }
8    }
9}

This is slightly heavier than streaming directly, but it gives you a familiar array-based enhanced for loop.

Choosing the Right Technique

Use toCharArray() when:

  • you only need basic character iteration
  • UTF-16 code units are acceptable
  • the string size is moderate and readability matters

Use an index loop when:

  • you need positions
  • you want to avoid a temporary char array
  • you are doing more complex in-place logic based on index

Use code points when:

  • Unicode correctness matters
  • emoji or supplementary characters may appear
  • the application processes user-visible text across languages

Performance Notes

For most application code, the performance difference between toCharArray() and charAt loops is not critical. The main design question is correctness and clarity.

If the string is large and you are inside a hot loop, charAt avoids allocating a new array. But if the logic is simple and readability is the main concern, toCharArray() is often perfectly fine.

Common Pitfalls

  • Trying to use the enhanced for loop directly on a String.
  • Assuming one Java char always equals one human-visible character.
  • Using toCharArray() when you also need the character index.
  • Ignoring surrogate pairs when processing emoji or extended Unicode.
  • Over-optimizing the loop style before deciding whether Unicode correctness matters.

Summary

  • You cannot apply Java's enhanced for-each loop directly to a String.
  • Use text.toCharArray() for ordinary character iteration.
  • Use an index-based loop when you also need positions.
  • Use codePoints() when full Unicode correctness matters.
  • Pick the iteration style based on correctness first, then performance concerns.

Course illustration
Course illustration

All Rights Reserved.