• 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Index of the last character of Strings

 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic