Sunday, March 22, 2009

Java String Internals

General info about Java Strings could be found in API Doc.
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);

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();

String world = "World";
String str = "Hello World";

String substr1 = str.substring(6, 11);
String substr2 = str.substring(6, 11).intern();


Illya Havsiyevych said...

Pool of unique strings is stored in «Perm Gen» memory

John clark said...

Nice piece of information provided...
Is anybody aware of java courses online ? i have enrolled myself in but i am not sure about this course so anybody has any kind of idea about this kind of course please let me know....

arumugam said...

Thank you for the info. It sounds pretty user friendly. I guess I’ll pick one up for fun. thank u

Java Courses

Kir said...

All said above are not valid for java 7 and above

vikas shukla said...

Very good post admin. Sufficient content is given here to understand every thing. For more information Please visit Java Internals

Harini R said...

thanks for shared wonderful information about giving the best information.its more useful and more helpful. great doing keep sharing
java training in chennai