Question

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?

Was it helpful?

Solution

My expectation is as follows:

  • the bytecode will contain both string literals because I don't expect javac (java -> bytecode compiler) to optimise that sort of things.
  • if the literal String is in the bytecode, it will go into the String pool

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top