Strings are immutable. So they can't be changed.
Strings store value internally in char array and have offset of the first character and characters count.
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
Example of initialization of empty String:
public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}
Strings could share the same character array. Check constructor and substring code:
// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
public String substring(int beginIndex, int endIndex) {
...
return ((beginIndex == 0) && (endIndex == count)) ? this :
new String(offset + beginIndex, endIndex - beginIndex, value);
}
Sample:
String str = "Hello World";
String substr = str.substring(6, 11);

Low level system implementation of String class follows Flyweight Design Pattern
/**
* Returns a canonical representation for the string object.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
Sample:
String world = "World";
String str = "Hello World";
String substr1 = str.substring(6, 11);
String substr2 = str.substring(6, 11).intern();

2 comments:
Pool of unique strings is stored in «Perm Gen» memory
Hey,
Nice piece of information provided...
Is anybody aware of java courses online ? i have enrolled myself in http://www.wiziq.com/course/12145-the-6-week-complete-java-primer-with-training-certificate but i am not sure about this course so anybody has any kind of idea about this kind of course please let me know....
Post a Comment