This week's book giveaway is in the Agile and Other Processes forum.
We're giving away four copies of The Journey To Enterprise Agility and have Daryl Kulak & Hong Li on-line!
See this thread for details.
Win a copy of The Journey To Enterprise Agility this week in the Agile and Other Processes forum! And see the welcome thread for 20% off.
  • 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:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

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.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!