aspose file tools*
The moose likes Java in General and the fly likes Index of the last character of Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Index of the last character of Strings" Watch "Index of the last character of Strings" New topic
Author

Index of the last character of Strings

Kezia Matthews
Ranch Hand

Joined: May 19, 2001
Posts: 107

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

Joined: Jun 11, 2001
Posts: 9
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

Joined: May 19, 2001
Posts: 107

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Index of the last character of Strings