naruto uzumaki naruto uzumaki - 1 year ago 83
Java Question

Why java compiler does not interns arrays?

Consider the below code

String s1 = "testString";
String s2 = "testString";
if(s1 == s2)System.out.println("equals!");

it prints equals!, (I am aware of String interning by the compiler)

String[] s1 = {"testString","teststring2"};
String[] s2 = {"testString","teststring2"};
if(s1 == s2)System.out.println("equals!");

however the above code does not work, why java compiler does not intern string array?

Answer Source

The reason is that a String is immutable. You can't alter it without creating a new instance. So it is safe to use the same instance where ever possible for matching strings. Strings are constant; their values cannot be changed after they are created.

How ever arrays are a different story. You can alter a array, just my assigning a new value to one of the fields.

s1[0] = "testString3"

If the compiler would use the same instance for s1 and s2 you would atomatically change both arrays. And that is likely not something you want to do. That is the reason why arrays are not interned.

Please also note that the string interning may have limits depending on the compiler and the compiler may choose to not intern some strings, depending on how many strings there are or how long the strings are. There is a internal string table that is controlled by the JVM option +XX:StringTableSize=n that determines the size of the string table used to store interned strings.

When it comes down to comparing strings is is always better to use the equals functions. Most implementations check for reference equality first anyway, before performing a more expensive checks.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download