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.

Java Java Objects Delivering the MVP Using Method Overloading

Laban Leuchovius
Laban Leuchovius
3,520 Points

Why do 'letters.length() == 0' equal to no input while 'letters.charAt(0)' gets the first character in the string?

So... If 'letters.length() == 0' equals no input, shouldn't 'letters.charAt(0)' get a non existing character? I mean, shouldn't 'letters.lenght() == -1' equal to no input?

Why do the different methods seem to start counting at different numbers? It seems like 'letters.length()' starts counting at 1 and 'letters.charAt()' starts counting at 0, like computers in general.

Is this true and why?

Thank you

1 Answer

Steven Parker
Steven Parker
220,925 Points

The difference is a size vs. an index. While a count (index) starts at 0 for the first item, a size is still the number of items just as you would count them with or without a computer. So something with a size of 0 is completely empty and has no items.

But if something has a size of 1, then it has one item, and the index number of the item is 0.

Laban Leuchovius
Laban Leuchovius
3,520 Points

Okay, thank you for your answer. Definitely cleared up some things.