For Each Loop
In Java, you can use a for-each loop, also known as an enhanced for loop, to iterate over elements of an iterable collection or array without explicitly controlling the iteration variables.
This loop simplifies the process of iterating through collections and arrays.
Traversing a String
In Java, you cannot use a for-each loop (enhanced for loop) to directly traverse each character of a string because a string is not considered an iterable collection like arrays.
Explanation
We first convert the string
str
into a character array using thetoCharArray()
method, which splits the string into individual characters.Then, we use a for-each loop to iterate over the characters in the
charArray
.We have now printed each individual characters of the string
Traversing an Array
Explanation
We define an array of doubles named
numbers
.We use a for-each loop to iterate over each element in the
numbers
array.The loop variable
num
takes on the value of each element in the array one by one, allowing you to perform operations or print the values as needed.
Last updated