iterate characters in string java code example

Example 1: iterate over string java

String str = "hello";
for (char c : str.toCharArray())
  //process c

Example 2: iterate each char in string in java

class Main {
  public static void main(String[] args) {

    // create a string
    String name = "Programiz";

    System.out.println("Characters in " + name + " are:");

    // loop through each element
    for(int i = 0; i<name.length(); i++) {

      // access each character
      char a = name.charAt(i);
      System.out.print(a + ", ");
    }
  }
}

Tags:

Java Example