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 trialSean Dunagan
7,068 PointsWhy wouldn't the String[3] array store 4 strings?
I'm sure he might explain this in a later video, but I don't understand why String[3] stores only 3 strings and not 4. Most language indexes start at 0, and for example would require you to enter a 2 there to store 3 values. Is java different somehow? I would assume that this code would store indexes for 0, 1, 2, and 3 and have a total of 4 entries.
2 Answers
Steven Parker
231,236 PointsIn the declaration, the value in the brackets is not the highest index, but the number of items to accommodate. So if you ask for 3, you get 3.
You're right about index number starting at 0, so the highest index will be one less than that number (2 in this case).
Does that clear it up?
Kamren Kowa
2,958 PointsShort answer: In a String array definition, the 3 you are referring to is really the SIZE of an array, not the index. So String[3] would be a String array with a size of 3. Calling index 3 of a String[4] would give you the 4th element in that array.
Ex:
String[] words = new String[4]; //Words has a size or length of 4
words[0] = "things";
words[1] = "and";
words[2] = "other";
words[3] = "stuff";
System.out.println(words.length); //This would be a size or length of 4
System.out.println(words[4]); //This would throw an ArrayOutOfBoundsException because the 4 here is the INDEX of the 5th item in the array, which does not exist within the bounds of the array.
Apologies if this is opaque at all!