proudandhonour proudandhonour - 3 months ago 13
Java Question

Which String Object is accessed?

As we know that when we create new String object by new keyword like this:

String str = new String("New String Will Have Two Objects");


It will create two objects of, one on java heap memory and other on String pool.

So when we call access
"str"
which string object is accessed(heap object or string pool object)?

According to my understanding the string pool object is get accessed, if yes then what happens to heap object?

Answer

If you are creating the String object with new

String str = new String("New String Will Have Two Objects");

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "New String Will Have Two Objects" will be placed in the string constant pool. The variable str will refer to the object in heap(non pool).

Method ‘intern()’ usage

This is best described by java docs

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

String str = new String("New String Will Have Two Objects");

str.intern();
Comments