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();
}
}
H e l l o W o r l d !
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()
. System.out.println()
to move the cursor to the next line after all characters have been printed.