Number of objects created during string concatenation

java, object, string

Solution

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 `invoke`d might allocated something themselves, and I have a very strong suspicion that StringBuilder.toString will allocate a `String` object.

Problem

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); ```

Original source