tags:

views:

91

answers:

5

Possible Duplicate:
How to know how many objects will be created with the following code?

I have following lines of code in a program

String str1 = "abc";
String str2 = str1;
String str3 = "abc";

I want to know how many objects are created when above 3 lines of code is executed.

A: 

3 objects, but they all use the same interned string (i.e. the string only exists once in the running JVM).

Coronatus
Your answer contradicts itself. Either there will be one object (correct) or three (incorrect). It can't be both.
Jon Skeet
3? What do you mean with object? `str2` is clearly only a reference.
Ishtar
So I think that the correct answer is that only 1 object is created here. Am I correct?
tek3
+2  A: 

only one object is created. The rest(str2,str3) are referred to internal string pool.

Suresh S
+2  A: 

2, 1 string object and the string contains 1 character array.

Michael Barker
Good catch. An array is an object, so it's (either) 2 (or 0, if "abc" has already been interned in the running jvm, see [codaddicts answer](http://stackoverflow.com/questions/3854553/how-many-objects-are-created-here-java/3854604#3854604))
Andreas_D
+3  A: 

All the three references refer to the same interned String object.

Prasoon Saurav
+2  A: 

It can create 0 or 1 object.

If there is already an interned String object with value "abc" no objects are created and if its not present, it gets created.

codaddict