Java: Interacting with Objects
The for-each loop is a special kind of loop in Java in that you can use it with groups of things. It looks like a for loop in some respects because it doesn’t actually use the keyword for-each — it uses the for keyword instead.
However, the associated statement is different. The associated statement begins with a variable to hold one element of whatever sort of collection of elements you want to process like this:
for (char Letter
It then has a colon. This colon means in. So, the statement now reads, for each Letter of type char in like this:
for (char Letter :
The last part is the collection of elements you want to process. Suppose you start with a String named MyString. You need to use the toCharArray() method to obtain a collection of char elements to process. So, the entire statement looks like this:
for (char Letter : MyString.toCharArray())
You read this statement as, For each Letter of type char in the MyString char collection, do something. At this point, you can process each of the elements (char variables) in MyString as you normally would with any other structure.
Early on, you really don’t need to worry about what a collection of elements precisely means. The main point is to understand the for-each loop, which you’ll use quite often.
Java 8 provides a special kind of for-each loop for lambda expressions. Once you find out how lambda expressions work, you can use the foreach() method with lambda expressions to simplify your code and make it run faster.