• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

Index of the last character of Strings  RSS feed

 
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.
 
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
Boost this thread!