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

Syntax of Array Construction (in Java)

If I have a class called 'Dogs', and I would like to make an array object within this class with 7 elements ...

Dogs[] breeds = new Dogs[7];

Okay, so, why does the class need to have the '[]' directly after it? Isn't that overkill? I feel like it would make sense like this: Dogs breeds = new Dogs[]; ...

I'm super curious about this. What is the point of this redundancy? Can anyone explain this to me in a way other than "that's just how it is"?

1 Answer

It's because Java is very strict about types and an array is a different type that a single object. So a "Dogs" is a single Dogs object and a "Dogs[]" is an array of Dogs objects.

So, it's kind of like the difference between 'int' and 'int[]', ... except I am using the class name as a type to say that 'breeds' is of the type 'Dogs[]' (an array of Dogs objects). I think that I am getting it, actually. Here's to thanking you for your help, Seth!