I always thought that an expression like this in java:
String tmp = "someString";
is just some kind of "syntactic sugar" for
String tmp = new String("someString");
As I recently decompiled my java app, I saw that ALL usages of
public static final String SOME_IDENTIFIER = "SOME_VALUE";
are replaced in code by just the value and the static final variable is stripped.
Doesn't instantiate this a new String everytime one wants to access the static final? How can this be considered as an "compiler optimization"??
String literals in Java source are interned, meaning that all literals with the same text will resolve to the same instance.
In other words, "A" == "A" will be true.
Creating a new String instance will bypass that; "A" == new String("A") will not be true.
String tmp1 = "someString";
String tmp2 = new String("someString");
String tmp3 = "someString";
if(tmp1 == tmp2)/* will return false as both are different objects
stored at differnt location in heap */
if(tmp1.equals(tmp2))/* will return true as it will compare the values
not object reference */
if(tmp1 == tmp3)/* will return true. see string literals and they are interned.
brief about them is they are stored in pool in permgen till
java 6.They are stored as part of heap only in java 7
Every time u create string literal with same value ,
it will refer from same location in pool instead of creating
object each time */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With