OneBite.Dev - Coding blog in a bite size

loop through each character in a string in java

Code snippet on how to loop through each character in a string in java

String str = "Hello World!";

for (int i = 0; i < str.length(); i++) {
  System.out.println(str.charAt(i));
}

This code creates a string called “str”, which is set to “Hello World!“. We then use a for loop to iterate through each letter in the string. For each letter, we use the charAt method to access the character at the index of the loop, and then print it out. The for loop runs until i < str.length(), which ensures it reaches the last character. The loop begins at 0, as the first character of a string is always at index 0.

java