2

How many string objects does the following code snippet generate in the string pool at runtime:

public class Test {
    public static void main(String[] args) {
       String string = new String("abc");      
       System.out.println("abc" == "def");  
   }
}

Does the second line generate a string object for def? Or is it ignored due to compiler optimization?

NightShade
  • 141
  • 1
  • 8

1 Answers1

0

The bytecode is as follows:

  public static void main(java.lang.String[] args) {
    /* L7 */
    0 new 2;
    3 dup;
    4 ldc 3;                  /* "abc" */
    6 invokespecial 4;        /* java.lang.String(java.lang.String autumn) */
    9 astore_1;               /* autumn */
    /* L8 */
    10 getstatic 5;           /* java.lang.System.out */
    13 iconst_0;
    14 invokevirtual 6;       /* void println(boolean arg0) */
    /* L10 */
    17 return;
}

So, I would say there is just one String generated. The "def" is stored in the constant pool.

René Winkler
  • 6,508
  • 7
  • 42
  • 69