Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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

Dawson Forbes
Dawson Forbes
487 Points

I always get: Bummer! java.lang.ArrayIndexOutOfBoundsException: 3 ()

I only get it in that task part and I've tried doing:

String lastSport = sports[3]; & String lastSport = sports[numberOfSports];

Both of them give them same error

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

hi Dawson,

To get the last sport value from the array, you will need:

String lastSport = sports[sports.length - 1];


String lastSport = sports[numberOfSports - 1];

This is because arrays are zero indexed. This means that the first value is at index 0 and the last one is at 2.

cheers, Swap

1 Answer

You've shown that you understand that arrays are 0-indexed (aka the first element has an index of 0). The length of the array is indeed 3, but because it's 0-indexed, if you write sports[3], you're actually asking for the FOURTH element in the array. To get the last (third) element, you want to use index 2.

String lastSport = sports[sports.length - 1];

Of course, you could replace the index with "numberOfSports - 1" or similar.