java – why string length -1

java – why string length -1

The indices of elements in Java (and most other languages) will always begin with 0. When considering an array/string the indices of the contained elements will start at 0 and end at (size of array/length of string – 1).

String string = Hello World

In the example above we have an array with 11 elements. Therefore the indices range from 0 to 10 (The string length minus one).

H is the first element in the string and is therefore indexed 0, i.e. string[0] = H.
e is indexed 1 i.e. string[1] = e, etc. The last element will be indexed 10 i.e. string[10] = d.

I think this explains it better than I do (and has pictures!) —

Read this for more info on manipulating and accessing arrays —

Strings are arrays of chars, and array indexes start to count from 0.

length is the amount of elements in that char array, but because the array starts at 0 the highest index is the amount of elements – 1 ==> .length() -1

java – why string length -1

The index for charAt starts at 0. ie. 0 is the first character.

This means a string of length 10, has chars between 0-9, not 1-10.

Leave a Reply

Your email address will not be published. Required fields are marked *