Depending on the version of java.lang.String (Java 7 Update 5 and earlier), a lookup array is used, and the starting index and length ( count ) of the actual string in this array. In these Java implementations, the underlying array may (substantially) take longer than the actual string, and the string does not necessarily begin at the beginning of the array.
For example, if you use substring , the lookup array may be identical to the lookup array of the original string, but only with a different start index and character. Therefore, using reflection to return a String support array does not work in all cases (or: this will lead to incorrect / unexpected behavior).
See, for example, http://www.docjar.com/html/api/java/lang/String.java.html String substring(int beginIndex, int endIndex) in the 1950 string (and below), which invokes the String(int offset, int count, char value[]) constructor String(int offset, int count, char value[]) on line 645 (and below). Here, char[] directly used as the base array, and offset and count are used as offset in the array and string length:
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex); } if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex); } return ((beginIndex == 0) && (endIndex == count)) ? this : new String(offset + beginIndex, endIndex - beginIndex, value); }
As Marco Topolnik points out, this is no longer the case with later versions of Java 7 . You should not depend on the details of the Java implementation (especially since this can change significantly between versions - as shown).
source share