English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java array

Java object-oriented (I)

Java object-oriented (II)

Java object-oriented (III)

Java Exception Handling

Java List

Java Queue (queue)

Java Map collection

Java Set collection

Java input output (I/O)

Java Reader/Writer

Java other topics

Java program iterates over each character in the string

Comprehensive Java Examples

In this tutorial, we will learn to traverse each character of the string.

To understand this example, you should understand the followingJava programmingTopic:

Example1Use for loop to traverse each character of the string

class Main {
  public static void main(String[] args) {
    //Create a string
    String name = "w3codebox";
    System.out.println( name + "The characters in ");
    //Loop through each element
    for(int i = 0; i<name.length(); i++) {
      //Access each character
      char a = name.charAt(i);
      System.out.print(a + "', ");
    }
  }
}

Output Result

w3The characters in codebox are:
n,h,o,o,o,

In the above example, we usedfor loopto access each element of the string. Here, we use the charAt() method to access each character of the string.

Example2:Use for-each loop traverses each character of the string

class Main {
  public static void main(String[] args) {
    //Create a string
    String name = "w3codebox";
    System.out.println( name + "The characters in ");
    //Use for-each loop traverses each element
    for(char c : name.toCharArray()) {
      //Access each character
      System.out.print(c + "', ");
    }
  }
}

Output Result

w3The characters in codebox are:
n,h,o,o,o,

In the above example, we use toCharArray() to convert the string to a char array. Then, we use for-each loop Access each element of the char array.

Comprehensive Java Examples