File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Very basic String question (substring method) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Very basic String question (substring method)" Watch "Very basic String question (substring method)" New topic

Very basic String question (substring method)

Rajeshwari Godbole

Joined: Dec 09, 2003
Posts: 1

In the Seirra and Bates book, page 387 has the following line:

"String methods use zero based indexes, except for the second argument of substring()."

This is confusing me since the method
public String substring(int beginIndex, int endIndex)
uses zero based index to calculate both beginIndex and endIndex (the only thing is that the endIndex is not included in the result)

Is this a typo or am I not understanding this correctly?

Ken Januski
Ranch Hand

Joined: Aug 08, 2002
Posts: 130
It's correct. If you have a string "abcd", substring(0,2) will give you "ab". That's because the first argument is 0 based, so you get "a",a nd the second is not 0 based, so you get "b". Absolutely inconsistent but correct.
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
I'm not sure that is the best way to explain it (well, I am sure that it isn't the best way to explain it but I like Kathy and Bert too much to say so). I think it is clearer to state that the second parameter is a zero-based index but it is exclusive not inclusive.

Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
I agree. Here's the link:
subject: Very basic String question (substring method)
It's not a secret anymore!