2

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?

Rajesh
  • 213
  • 4
  • 15
  • 3
    Compile the code and check with `javap`. – Sotirios Delimanolis Jan 16 '14 at 14:55
  • 2
    The Java compiler (java -> bytecode) will probably leave it as is, the JIT compiler (bytecode -> assembly) will almost certainly remove the first line... – assylias Jan 16 '14 at 14:57
  • Which java compiler are you refering to? – Oswald Jan 16 '14 at 14:57
  • 1
    @assylias there is no second compiler. Only an interpreter. – André Stannek Jan 16 '14 at 14:57
  • 1
    @AndréStannek huh... no, the JIT compiler is not an interpreter, it does transform bytecode to native code... I have clarified my comment. – assylias Jan 16 '14 at 14:59
  • 1
    Andre that is incorrect, there is a Just-In-Time (JIT) compiler in all the major JVM implementations. – Jake Cobb Jan 16 '14 at 14:59
  • http://stackoverflow.com/questions/4918399/what-type-of-memory-heap-or-stack-string-constant-pool-in-java-gets-stored - this will be helpful for you. – user Jan 16 '14 at 15:02
  • @assylias Thank you... I did javap and saw no optimization in bytecode but thanks for bringing in JIT as it would have never clicked my mind and i got to know that all optimization is done by jit in java. – Rajesh Jan 16 '14 at 15:27
  • The compiler will create two objects one for `a` and another for `b` but reference will be same. – Qadir Hussain Jan 16 '14 at 15:34
  • 1
    @assylias Huh, I learned that differently. But after a little research I have to admit you're right. Thanks! – André Stannek Jan 16 '14 at 15:42

1 Answers1

2

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.

assylias
  • 321,522
  • 82
  • 660
  • 783