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

Naomi Mitchell
PLUS
Naomi Mitchell
Courses Plus Student 782 Points

I did not understand anything about the For each loop please could someone explain this to me and how i would use it?

The video shows you the code but i dont really understand it nor the 'read more' article

Naomi Mitchell
Naomi Mitchell
Courses Plus Student 782 Points

sorry i meant what does this mean String sweet : sweetFlavours
What do the semi colons mean in java? Its shown in 'For Each' and 'Nesting Loops' please?

I didn't understand either video.....

2 Answers

// First of all, as you can see we have an array of names and the name of the array is jacksons
String[] jacksons = {"Michael", "Jackie", "Tito", "Jermaine", "Marlon", "Randy"};

// Then we have our for each loop
for (String jackson : jacksons) {
    console.printf("%s Jackson %n", jackson)
}

// Let's break it apart
// String jackson( String jackson ) is creating and holding each "name" of jacksons( jacksons ) array
// So when the for each first encounter the name Michael, it will assign that name to the string jackson
// and then it will use the console.printf to print 'Michael Jackson'
// %s in the printf is just a placeholder for the string jackson
// %n is creating a new line after it.
// So for each loop would run through all the names in the array jacksons and print the following:

// Michael Jackson
// Jackie Jackson
// Tito Jackson
// Jermaine Jackson
// Marlon Jackson
// Randy Jackson

// Don't overthink it. All for each loop does is run through each element in an array and for each element it performs an action
// in this case, it prints the 'name Jackson'
String jackson : jacksons

// I hope this helps.

// Remember, keep practicing. Create you own arrays and use for each loop, see how it works.
// Here is an example

String[] Colonies = {"Connecticut", "Rhode Island", "Massachusetts", "New Hampshire", "Delaware", "Pennsylvania", "New Jersey", "New York", "Maryland", "Virginia", "North Carolina", "South Carolina", "Georgia"};

for (String colony : Colonies) {
    console.printf("%s %n", colony)
}

Ohh, the ":" just means that it's a For each loop. Nothing special about it. It just tells Java that it's a For each loop. You can think of it as "in". For example:

  • (String[] sweet : sweetFlavours)
  • sweet in sweetFlavours