Skip to content

What is the easiest/best/most correct way to iterate through the characters

There are several ways you can iterate through the characters of a string in Java. Here are a few options:

  1. Using a for loop:

java
String str = "Hello";
for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    // do something with c
}
  1. Using a for-each loop:

java
String str = "Hello";
for (char c : str.toCharArray()) {
    // do something with c
}

Note: toCharArray() allocates a new array, which may impact memory usage for large strings.

  1. Using an iterator:

java
import java.util.Iterator;

String str = "Hello";
for (Iterator<Character> it = str.chars().mapToObj(c -> (char)c).iterator(); it.hasNext(); ) {
    char c = it.next();
    // do something with c
}

All of these methods are correct and which one you choose will depend on your personal preference and the context in which you are using it. The for loop is generally the most performant and memory-efficient. The for-each loop is the most readable but allocates a temporary array. The iterator approach is valid but unnecessarily complex for this use case; consider str.chars().forEach(c -> { char ch = (char) c; /* ... */ }) for a cleaner stream alternative.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.