Google News
logo
Java Program to Iterate through each Characters of the String
In the following example of Java program to iterate through each character of a string :
Program :
public class IterateString {
    public static void main(String[] args) {
        String str = "Hello World!";
        // Iterate through each character of the string using a for loop
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            System.out.print(ch + " ");
        }
        System.out.println();
    }
}
Output :
H e l l o   W o r l d !
In this program, we first declare a string variable str and initialize it with the string "Hello World!". We then use a for loop to iterate through each character of the string. Inside the loop, we use the charAt() method to retrieve the character at the current index i, and we print it to the console using System.out.print().

Finally, we print a newline character using System.out.println() to move the cursor to the next line after all characters have been printed.