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 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
231,268 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.