Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java For Each

In the for each loop how does the program know what the value of "jackson" is?

I'm not quite sure how to ask this but I'm having a difficult time understanding how the program knows the value of jackson in the for each loop. In the for loop jackson was assigned a value which made sense to me. I feel like there's something fundamental about the for each loop I'm not getting. Any insight would be appreciated!

2 Answers

K Cleveland
K Cleveland
21,839 Points

So looking at the video, it looks like jacksons is an array of strings. Like this:

String[] jacksons = {"Michael", "Jackie", "Tito", "Jermaine", "Marlon", "Randy"};

Each of those elements in jacksons is a string.

//for each string in the array jacksons
for (String jackson : jacksons) {

//print to the console the value of jackson
console.printf("%s Jackson %n", jackson);

}

In the above code, when you write

for (String jackson : jacksons) 

the for each loop reads the first element from the array, and sets that value to the variable named "jackson". The first time the for each loop runs the jackson variable will be set to "Michael". Then, the console.printf line prints out the name Michael Jackson. The second time, the jackson variable will be set to "Jackie, and so Jackie Johnson will be printed to the console. And so on, until the end of the array.

Hope this helps!

Thanks Cleveland!

Ha!!!! I figured it out... epic brain fart!