The substring (int beginindex, int endIndex) methods are different in JDK6 and JDK7. Understanding their differences allows us to better use this approach. For convenience, the following replaces substring (int beginindex, int endIndex) with substring ().
1. What did substring () do?
The substring (int beginindex, int endIndex) method returns a String object that begins with Beginindex and ends with EndIndex-1.
String x = "abcdef"=x.substring (1,3); SYSTEM.OUT.PRINTLN (x);
Output:
Bc
2. What happens when substring () is called?
You might think that because X is immutable, when x is processed by substring (1,3), it points to a new string object as follows:
However, this diagram does not correctly represent what is really going on in the heap memory. So what is the difference between JDK6 and JDK7 when calling the substring () method?
3. Substring () in JDK 6
String is implemented by a character array, in JDK6, the string class consists of three parts: charvalue[], int offset, int count. They are the real arrays that are used to store characters, and the first element of the array is used to store the length of the characters.
When the substring () method is called, a new string object is created, but the value of the string object still points to the same array in heap memory. The real difference is their count and offset.
The following code has been simplified to include only the key parts that explain the problem.
//JDK 6String (intOffsetintCountCharvalue[]) { This. Value =value; This. offset =offset; This. Count =count;} PublicString substring (intBeginindex,intEndIndex) { //Check Boundary return NewString (offset + beginindex, EndIndex-beginindex, value);}
A problem with substring () in 4.JDK 6
If you have a very long string object, you only use a small portion of it each time you pass substring (). There is a performance problem, and for JDK6, the following code can be used to solve this problem, which creates a true substring object:
x = x.substring (x, y) + ""
5. Substring () in JDK 7
In JDK7, the substring () method actually creates a new array in heap memory, which is an improvement in JDK7.
//JDK 7 PublicString (CharValue[],intOffsetintcount) { //Check Boundary This. Value = Arrays.copyofrange (value, offset, offset +count);} PublicString substring (intBeginindex,intEndIndex) { //Check Boundary intSublen = EndIndex-Beginindex; return NewString (value, Beginindex, Sublen);}
Original address:
http://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/
(iii) Comparison of SUBSTRING () methods in--jdk6 and JDK7