How many String object..?

前端 未结 6 1334
礼貌的吻别
礼貌的吻别 2021-01-18 13:36

Me and my friend was discussing on Strings and we stuck on this:

String str = \"ObjectOne\"+\"ObjectTwo\";

He says total three Object will

6条回答
  •  臣服心动
    2021-01-18 14:31

    You can easily check this yourself:

    1. Compile the following program:

      public static void main(String[] args) {
          String str = "ObjectOne"+"ObjectTwo";
          System.out.println(str);
      }
      
    2. Inspect the bytecode emitted by the compiler:

      javap.exe -v Test.class
      

    For the main method, this prints:

      public static void main(java.lang.String[]);
        flags: ACC_PUBLIC, ACC_STATIC
    
        Code:
          stack=2, locals=2, args_size=1
             0: ldc           #16                 // String ObjectOneObjectTwo
             2: astore_1      
             3: getstatic     #18                 // Field java/lang/System.out:Ljava/io/PrintStream;
             6: aload_1       
             7: invokevirtual #24                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
            10: return        
          LineNumberTable:
            line 6: 0
            line 7: 3
            line 8: 10
          LocalVariableTable:
            Start  Length  Slot  Name   Signature
                   0      11     0  args   [Ljava/lang/String;
                   3       8     1   str   Ljava/lang/String;
    }
    

    As you can see, the programm uses the ldc bytecode instruction to refer to a single, already loaded string instance (which is loaded when Test.class is). No new object is therefore created during execution of that line.

    The compiler is required to perform this optimization by the Java Language Specification :

    The String object is newly created (§12.5) unless the expression is a compile-time constant expression (§15.28).

提交回复
热议问题