Java – Iterate over characters in String

To iterate over characters in a string in Java, you can use a loop statement to iterate over the indices of characters from the first character to the last character, and access the character in the string using String.charAt() method.

Or, you can convert the given string to a character array, and use a For-each loop to iterate over the array of characters.

1. Iterate over characters in String using For loop in Java

You can iterate over the characters in a string using a For loop in Java. Write a For loop that increments an index counter from zero upto the length of the string. During each iteration, use the index and get the character in the string using String.charAt() method.

Now, let us write a Java program, to iterate over the characters of a string "Hello World" using a For loop.

Java Program

</>
Copy
public class Main {
	public static void main(String[] args) {
		String myString = "Hello World";
		for(int i=0; i<myString.length(); i++) {
			System.out.println(myString.charAt(i));
		}
	}
}

Output

H
e
l
l
o
 
W
o
r
l
d

2. Iterate over characters in String using While loop in Java

Similar to the previous example, you can use a While loop and iterate over the characters using an index counter in the loop.

Now, let us write a Java program, to iterate over the characters of a string "Hello World" using a For loop.

Java Program

</>
Copy
public class Main {
	public static void main(String[] args) {
		String myString = "Hello World";
		int i=0;
		while(i<myString.length()) {
			System.out.println(myString.charAt(i));
			i++;
		}
	}
}

Output

H
e
l
l
o
 
W
o
r
l
d

3. Iterate over characters in String using For-eacg loop in Java

We can get the characters in the string as an array using String.toCharArray() method, and then use a for-each loop to iterate over the characters in the character array.

Now, let us write a Java program, to iterate over the characters of a string "Hello World" using a For-each loop.

Java Program

</>
Copy
public class Main {
	public static void main(String[] args) {
		String myString = "Hello World";
		for(Character ch: myString.toCharArray()) {
			System.out.println(ch);
		}
	}
}

Output

H
e
l
l
o
 
W
o
r
l
d

Conclusion

In this Java String tutorial, we have seen how to iterate over the characters in a string in Java using a For loop, While loop, or For-each loop statement, with examples.