Campbell Ritchie wrote:That blog is suggesting bad programming practice, viz inspecting the implementation rather than the public interface.
Nothing about backing arrays there, and that is from Java1.2 API. I found a β version of the Java1.1 API, which has thissubstring
public String substring(int beginIndex,
int endIndex)
Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
Examples:
"hamburger".substring(4, 8) returns "urge"
"smiles".substring(1, 5) returns "mile"
Parameters:
beginIndex - the beginning index, inclusive.
endIndex - the ending index, exclusive.
Returns:
the specified substring.
Throws:
IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
It might have been useful to warn about the potential memory problem, particularly in the early days when memory was more expensive.substring
public String substring(int beginIndex,
int endIndex)
Returns the substring of a String. The substring is specified by a beginIndex (inclusive) and an endIndex (exclusive).
Parameters:
beginIndex - the beginning index, inclusive
endIndex - the ending index, exclusive
Throws: StringIndexOutOfBoundsException
If the beginIndex or the endIndex is out of range, or if the beginIndex is greater than the endIndex..
Jeff Verdegan wrote:First this topic has nothing to do with Threads and Synchronization. It would have been better placed in Beginning Java. In the future, please CarefullyChooseOneForum (<-- link).
As to your question, a String object has something the following:
Now, when you construct a brand new String that's not part of some other String, offset will be 0 and int will be equal to value.length. That means that this String uses the entire array.
So this String uses character 0 through character 4 (5 characters) in the array {'a', 'b', 'c', 'd', 'e'}
If we do
In this case, s2 has a reference to the same char[] as s1 (so that we can avoid the cost of creating a new array and copying characters). S2's offset is 1, meaning it starts at index 1, which is where 'b' is, and the count is 2, meaning it uses 2 characters, so s2 is "bc"
Consider Paul's rocket mass heater. |