This week's book giveaway is in the OCMJEA forum. We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line! See this thread for details.
s.replace(1, 3, "24");
This replaces the part of s between index 1 (inclusive) and index 3 (exclusive) by "24". That is, replaces characters at index 1 and 2 with 24, so you get 424789.
All code in my posts, unless a source is explicitly mentioned, is my own.
Joined: Jan 04, 2009
Joined: Dec 16, 2008
No problem, Alessandra!
Remember that pretty much any indexable thing in Java (arrays, String instances, StringBuilder and StringBuffer instances) is indexed starting at 0 (I don't know if there is any exception to that.) Also, when you provide two indexes to specify a range, normally (again, I don't know if there is any exception) the first index will be inclusive and the last index will be exclusive (the index of the first element after the range itself.)
Inclusive means that that value is considered in the operation, eg: a definition of 1 (inclusive) to 3 (exclusive) indicates that 1 should be considered, as it's inclusive, while 3 should not be considered (as it's exclusive).
Hence, the above example for integers would have a list of : 1, 2.
Joined: Feb 13, 2005
My confusion has to do with the fact that in SCJP 5 by K&B in CH6 under the explanation for
public String subString(int begin, int end)
says "the first argument represents the starting location (zero based) of the substring. .... Unfortunately the ending argument is not zero based, so if the second argument is 7, the last character in the returned String will be in the original String's 7 position which is index 6 "
Could any one of you please clarify this?
ex: String x = "0123456789";
The output is "567"
0 1 2 3 4 5 6 7 8 9
^ ^ ^ ^ ^ ^ ^ ^ ^ ^
In this case position 5 should be 4 if the first argument is zero based. Then why is it 5?
In my opinion K&B should give a better explanation than confusing us.
0,1,2,3,4 where 4 is in the 5th position. So does that mean that index and position are not the same? I am still confused.
Suppose we have
The output should be D E. ( D is in index 3 and E is in index 5. Another way to think as has been mentioned by Alessandra and Ruben is the first argument inclusive --> D , and second argument exclusive i.e. exclude F at index 5.)
Is this correct?
The best way to think about this is as given at the end of the SCJP FAQ and in one of the explanation of inquisition. Just think of the indexes as being in between the characters. Just look at this string (ignore the space between characters)
Now if the substring method is like this substring(2,5);, then the resulting string would be CDE. Now you don't need to worry about 0 based and one based indexes. This applies to all the index based methods of String class and StringBuffer and String Builder class (eg. the delete method of StringBuffer and StringBuilder class)...