To iterate over the letters in a word in Java, you can use a for
loop or the forEach()
method of the CharSequence
interface.
Here's an example of how to use a for
loop to iterate over the letters in a word:
public class Main { public static void main(String[] args) { String word = "hello"; // Iterate over the letters in the word and print each letter to the console for (int i = 0; i < word.length(); i++) { char letter = word.charAt(i); System.out.println(letter); } } }
This code creates a string and then uses a for
loop to iterate over the letters in the word. The loop variable i
is initialized to 0, and the loop continues until it reaches the last index of the word (word.length() - 1
). The charAt()
method is used to retrieve the letter at the current index.
Alternatively, you can use the forEach()
method of the CharSequence
interface to iterate over the letters in a word:
public class Main { public static void main(String[] args) { String word = "hello"; // Iterate over the letters in the word and print each letter to the console word.chars().forEach(c -> System.out.println((char) c)); } }
This code uses the chars()
method of the CharSequence
interface to create a stream of integers representing the characters in the word, and then uses the forEach()
method to iterate over the stream and print each letter to the console. The forEach()
method takes a Consumer
object as an argument, in this case a lambda expression that casts the integer value to a char
and prints it to the console.