10

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); 
4
  • 1
    It is implementation dependent - probably 5 on hotspot... Why does it matter? Commented Feb 12, 2014 at 9:47
  • 1
    I can see only 1 String object created here. See my answer. If anyone thinks something else, please provide an explanation rather than saying random numbers. Commented Feb 12, 2014 at 9:55
  • this questions is not clear on if compile time created objects should also be considered or not; all provided answers at the moment leave those out. On compile time there are 4 allocations, 2 inherit from Object (both Strings) Commented Feb 12, 2014 at 12:39
  • I agree with @assylias. This doesn't appear to be particularly important. I don't think knowing this detail makes one a better java developer Commented Feb 12, 2014 at 14:03

10 Answers 10

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The comments in the code suggest that only one StringBuilder object is created then all other given arguments for the + operator are appended to the StringBuilder object and at the end the toString() method is called from the StringBuilder object,and the returned String value is passed to the print() method.
4

This will create a StringBuilder object (and whatever this object uses internally), add the values and finally the StringBuilder will create a String object with the result.

Comments

2

The code

int i=0; int j=1; System.out.print("i value is "+ i + "j value is "+j); 

Creates 3 objects.

My Reason:

The basic data types in Java are not objects and does not inherit from Object. so int i=0; and int j=1; does not make an object.

Now System.out.print("i value is "+ i + "j value is "+j); which contains String which are immutable, and the operations on string are costly.We can split the operations as this.

("i value is ").concat(i) // creates one object let say obj1 obj1.concat("j value is ") //creates another let say obj2 obj2.concat(j) // creates the final string let say obj3; 

In an example string operation str1.concat(str2) is done by using two String objects and it creates the third one and change the reference making an illusion that its actually the first string object ie str1. Thus the str1 will be having a new String which contains the value of the old str1 and the str2 concatenated.

This is what i believe with my limited knowledge. Correct me if i am wrong.

5 Comments

I would argue that ("i value is").concat(i) makes 2 objects. First it has to make "i value is". Then it has to concat i to it to return a new string.
It's obj1="i value is";obj2=obj1.concat(i);obj3="j value is";obj4=obj2.concat(obj3);obj5=obj4.concat(j);
"i value is" will already be in existence before the statement runs.
@Cruncher I have looked for that, but i haven't found any valid documentations for that. I believe that the ("i value is").concat(i) consider i value is as an input rather than an object. Do you have any valid documentation to support your argument.?
@cHao Are you saying that an object is created for "i value is" before the concat operation is done.? Do you have any supporting document, i like to learn what's going on inside .!!
1

Only 1, the String object get concatenated.

Comments

1

The code is converted, by the compiler, to something like this:

int i=0; int j=1; StringBuilder temp = new StringBuilder(); // creates a StringBuilder temp.append("i value is "); // creates or re-uses a String temp.append(i); // might create a String temp.append("j value is"); // creates or re-uses a String temp.append(j); // might create a String String temp2 = temp.toString(); // creates a String System.out.print(temp2); 

It depends on whether you count the "i value is " and "j value is " strings, which are created once and then re-used.

If you do count them, then at least 4, otherwise at least 2.

Actually, each String has its own char[] that actually stores the string. So that's 7 or 3, instead of 4 or 2.

StringBuilder has a char[] as well and might have to create new char[]'s as you add more data to it. String.valueOf or System.out.print might also create objects behind your back and there's no way you can know about them without external tools. Hence "at least".

3 Comments

Are you sure about the temp.append(String.valueOf(i))? Since there is an append variant taking an int argument I would assume this is used.
@Ɍ.Ɉ This is not conclusive. The characters of the string representation could be determined and added individually without creating a String. Just the overall effect is the same.
Just tested it, it does call temp.append(i). Edited answer.
1

If it is indeed implementation dependent, then if it is evaluated to:

StringBuilder sb = new StringBuilder("i value is "); sb.append(i); sb.append(j); String newStr = sb.toString(); 

There will be 2 objects.

5 Comments

I see at least two here!
So during concatenation it will actually be two objects, right? StringBuilder and String
Commenters, please suggest a correction instead of saying: THAT'S WRONG.
"i value is" is one. StringBuilder#append may create additional strings + the final one.
Do we care about the objects being created by the StringBuilder? There's a backing store of some kind (probably an array, i haven't looked), which may be resized over the course of the operation.
0

Only 1 i.e for printing the String .

Thumb rule - Whenever concatenation of strings are done , a new object is created.

Comments

0

String is immutable means that you cannot change the object itself.
While performing concatenation every time new string objects are created.
So in above example

  1. int i
  2. int j
  3. "i value is "
  4. "i value is "+ i
  5. "i value is "+ i + "j value is "
  6. "i value is "+ i + "j value is "+j

Total six objects are created in above example.

2 Comments

int is a primitive type, not an object. Integer on the other hand is.
@xlm so it depends on if during concatenation, the primitive is ever converted to an Integer. I doubt that to be the case.
0

5 objects

  1. "i value is ".A String object will be formed.
  2. "i value is "+i.This concatenation operation will form 2nd Object.
  3. "j value is " will form third object.
  4. "i value is "+i + "j value is ".4th object formed because of concatenation.
  5. "i value is "+ i + "j value is " + j .This last concatenation will form 5th object.

Comments

0

You should consider 2 points here:

  1. When you say String is immutable, it will create a new object if you try to change the value.
  2. String object will be created when you write code using Literal(String s = "Pool") way or using new keyword (String s = new String("Heap and Pool"), here new keyword refers heap, the Literal "Heap and Pool" refers String constant pool).

In this case the above answer is correct. Five String objects will be created.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.