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

Jon-Ryan Maloney
Jon-Ryan Maloney
5,704 Points

Struggling to understand Java arrays

I'm struggling to understand this logic from the Java arrays workshop:

String[] names = {"Ben", "Jerry", "Geoff", "Ryan"};

Cow[] cows = new Cow[names.length];

for (int i = 0; i < (names.length); i++) {
  cows[i] = new Cow(names[i]);
}

for (Cow cow : cows) { 
  console.printf("%s%n",
                 cow.getName());
}

Why did we declare a new array of Cows if we already did with the String array above it? Why isn't that redundant?

Also, why did we need to use two for loops?

Lukas Baumgartner
Lukas Baumgartner
14,817 Points

I've not watched the video, but:

Why did we declare a new array of Cows if we already did with the String array above it?

I guess it's just to show how things work. You maybe won't do it that way in a "real" program.

Also, why did we need to use two for loops?

Also just a guess, but I think they just want to let you know about the kinds of for loops you can use on arrays. The first one is a "normal" counting for loop, nothing special about it. The second one is an enhanced for loop, you can read it out loud kind of that way: for each Cow in the cow array, do something

Maybe you find this interessting: https://stackoverflow.com/questions/11555418/why-is-the-enhanced-for-loop-more-efficient-than-the-normal-for-loop

1 Answer

Jon-Ryan Maloney
Jon-Ryan Maloney
5,704 Points

Thanks Lukas. I just got overwhelmed with the multiple steps that didn't seem necessary. I'll check out your link.