Java Program to Iterate Through Each Character of a String

In this program, we will learn to iterate through each character of a given string. We can iterate through each character of a string by using the charAt() method or by converting the string to a character array using the toCharArray() method.

Here is an example of how you can iterate through each character of a string using the charAt() method.


Java Program to Iterate Traverse Each Character of a String

public class IterateStringExample {
  public static void iterateString(String str) {
    for (int i = 0; i < str.length(); i++) {
      System.out.println(str.charAt(i));
    }
  }

  public static void main(String[] args) {
    String str = "Hello World!";
    iterateString(str);
  }
}
Output
H
e
l
l
o

W
o
r
l
d
!

In this example, the iterateString method takes a string as a parameter and uses a for loop to iterate over the characters of the string. In each iteration, the method uses the charAt() method to get the character at the current index, and then it prints the character to the console.

Another way to iterate through each character of a string is by converting it to a character array using the toCharArray() method as following:

public class IterateStringExample {
  public static void iterateString(String str) {
    char[] chars = str.toCharArray();
    for (char c : chars) {
      System.out.println(c);
    }
  }

  public static void main(String[] args) {
    String str = "Hello World!";
    iterateString(str);
  }
}
Output
 
H
e
l
l
o

W
o
r
l
d
!

In this example, the iterateString method takes a string as a parameter, it converts the string to a character array using the toCharArray() method, then it uses a for-each loop to iterate over the characters in the array, and in each iteration, it prints the current character to the console.