Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Index of the last character of Strings

 
Kezia Matthews
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The index of the first character of a String is zero and the index of the last character (if I am not wrong,) is length of the String minus one.
Using charAt():

Prints:
Length of str is 5
Character at zero position is H
Last character is o

The above code throws StringIndexOutOfBoundsException, because when the index starts with zero the last element would be at position length of the string minus one.
Using getChars():

Prints:
Hell<junk here>
Hello
Why is the last character that the line marked "Line 1" contain junk and why is the line marked "Line 2" not throw an Exception?
Kezia.
 
Felix Ulrich
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you look at the getChars entry in the Java 2 API docs, you'll see that the endIndex you pass in refers to the index after the last character you want to copy, rather than the actual index of the last character, as you are assuming.
 
Kezia Matthews
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Sorry! I should've looked at the getChars function definition not just the function declaration in the java doc before posting such a question.
Thanks Felix for your help.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic