public class Test { public static void main(String[] args) { String str = new String(new char[]{'H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'}); System.out.println(str.charAt(str.length() - 1 )); } } 

I don’t understand why it gives out d, if we assume the length is 11. And we make 11 - 1 = 10 and why it gives out d.

  • five
    Because the numbering starts from 0 , not from 1 . - Drakonoved Nov.

1 answer 1

What do you expect?

The charAt method of the String class charAt character of the string at the specified index. Documentation .

Indexation in lines not from 1, but from 0, therefore the character with index 10 is the 11th character, that is, 'd'.