Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

java - Number of objects created during string concatenation

Can someone please tell me how many objects will be created on executing the System.out.println statement in the below code

int i=0;
int j=1;
System.out.print("i value is "+ i + "j value is "+j);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you really want to know what's going on, why not look at the bytecode?

I wrapped your code in a main function, compiled it and then disassembled it with javap -c Test.class. Here's the output (using a Oracle Java 7 compiler):

Compiled from "Test.java"
class Test {
  Test();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]);
    Code:
       0: iconst_0
       1: istore_1
       2: iconst_1
       3: istore_2
       4: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
       7: new           #3                  // class java/lang/StringBuilder
      10: dup
      11: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
      14: ldc           #5                  // String i value is
      16: invokevirtual #6                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      19: iload_1
      20: invokevirtual #7                  // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      23: ldc           #8                  // String j value is
      25: invokevirtual #6                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      28: iload_2
      29: invokevirtual #7                  // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
      32: invokevirtual #9                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      35: invokevirtual #10                 // Method java/io/PrintStream.print:(Ljava/lang/String;)V
      38: return
}

The only object that gets allocated in this method is the StringBuilder (by the new instruction at position 7). However, the other methods that are invoked might allocated something themselves, and I have a very strong suspicion that StringBuilder.toString will allocate a String object.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...