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

Android Build a Simple Android App (2014) Coding the Fun Facts Using an Array

Dan Maia
Dan Maia
1,078 Points

String lastSport = sports[5]; What is wrong with this answer adding a String object to the last of the array

It worked adding a variable to the beginning of the array why wont this work for the last element of the array. I am confused?

Array.java
String[] sports = { "Basketball", "Baseball", "Tennis" };
String bestSport = sports[0];
int numberOfSports = sports.length;
String lastSport =  sports[5];

2 Answers

You're close to what the task is asking for, instead of using the 5 that you have for the index, to use the last element in the array, which would always be [array.length - 1] or in this case [numberOfSports - 1].

Michael Flynn
Michael Flynn
3,084 Points

Well for starters you only have 3 elements in the array, so the last element is at position 2 right now (remember arrays start at zero!).

Also you are not adding an element to the array, just setting a variable to the value at the position you specify!

To add an element to the array position you'd do something like sports[5] = "soccer";

Which would add the string "soccer" to the array at position 5.

You also couldn't do sports[5] = "soccer";

This is because the array was created to have 3 elements and once an array is created it cannot be resized. An ArrayList, however, can change size.