Strings are interned per JVM or per class ?

R

Razvan

Hi!




The following code prints 'equal' on my system (jdk 1.4):


public class CDummy
{
public static void main(String args[])
{
System.out.println("CDummy.");

String temp = "unique";

if (temp == CSomeDummy.s1) System.out.println("equal");
}
}

class CSomeDummy
{
static String s1 = "unique";
}


Is this behaviour dictated by specifications ? Is it possible that
temp and CSomeDummy.s1 references will not be equal because the string
are in different classes ? Perhaps this is implementation dependent.



Regards,
Razvan
 
T

tony vee

Hi Razvan

You have come accross a Java memory efficiency mechanism. To make Java more
memory efficient, the JVM sets aside a special area of memory called the
String constant pool. When the compiler encounters a String literal, such as
your "unique" literal, it checks the pool to see if an identical String
already exists. If a match is found, the reference to the new literal is
directed to the existing String and no new String literal object is
created - the String simply now has an additional reference pointing to it.
Since you have already created the "unique" String object and assigned the
reference to it to the s1 variable, instead of the compiler creating another
one, it simply assigns the reference of the exisiting one to the new temp
variable. So both s1 == temp and s1.equals(temp) will equate to true. If you
wanted to create a string and not use an existing one in the pool, do it
explicitly -

String temp = new String("unique");

and not by instantiating via a short cut mechanism, i.e.

String temp = "unique";

Doing it the long way will mean that s1.equals(temp) is still true, but s1
== temp is now false

As a quick aside:

Remember that Strings are immutable:

String s1 = "unique";
String temp = s1;

System.out.println(s1.equals(temp)) //prints true

//at this point there is only one String object referred to by two reference
variables

s1 = "not unique";

// this line creates a new String object and sets the value of s1 to point
to it, but this means that temp is now poining to a
different String object (that being the original one):

System.out.println(s1.equals(temp)) //prints false
System.out.println(s1) // prints not unique
System.out.println(temp) // prints unique

Enjoy!

Tony
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,774
Messages
2,569,599
Members
45,175
Latest member
Vinay Kumar_ Nevatia
Top