Reputation: 213
If i have a code:
String s="a";
s="b";
Note that there is no reference or use of s
in between these two statements.
Will java compiler optimize this, ignore the first assignment and only store "b"
in string pool?
Upvotes: 2
Views: 781
Reputation: 328598
My expectation is as follows:
This can be tested with the following code:
public static void main(String[] args) throws Exception {
String a = new String(new char[] { 'a' }); //don't use string
String b = new String(new char[] { 'b' }); //literals or they
String c = new String(new char[] { 'c' }); //will be interned!
String s = "a";
s = "b";
System.out.println("a is interned? " + (a.intern() != a));
System.out.println("b is interned? " + (b.intern() != b));
System.out.println("c is interned? " + (c.intern() != c));
}
which prints:
a is interned? true
b is interned? true
c is interned? false
As expected.
Note however that the JIT compiler, when it kicks in, will almost certainly get rid of the unused statement, but that won't remove the string from the pool.
Upvotes: 2