+ 3
How many objects are created?? In java.
String s="hey"; String s1="hey"; String s2=new String("hey"); String s3 =new String("hey"); no. of objects. explain how? đ
12 Answers
+ 1
String s="hey";//object 1
String s1="hey";//referring to object 1
String s2=new String("hey");//object 2
String s3 =new String("hey");//object 3
+ 4
3 Strings were created.
s1 points to s in the SCP.
s2 and s3 used 'new' without interning the String. Thus are created as separate Strings.
Keep in mind this is not the number of Objects created.
Strings use a char[] to keep track of each character (The value of the String).
So, 2 Objects were created when s was.
I think (not 100% sure), the char[]'s from s1, s2 and s3 would all use the same reference from the pooled s. So, 4 objects would be created in total.
If I'm wrong about that happening then 6 objects would be created. 2 for each String, the String itself and the char[] it uses internally.
There is also a possibility of local variables that create objects in the String classes constructor. Which could mean even more objects would be created. Although, those would be temporary.
+ 2
unfortunately false, but near correct. let me help you, only s and s1 referring to same memory location.
s2 and s3 are referring to be memory location that contains "hey".
+ 2
No fella, and no 4 no 6 this is wrong answer.
+ 2
correct answer is 3,
Two with new keyword s2 and s3 and
one which referred by s and s1.
+ 2
Indeed, as part of making a String a character array is created - the constructor from the source code:
public String() {
         this.offset = 0;
         this.count = 0;
         this.value = new char[0];
 }
http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java
Other constructors create non-zero size arrays as required, so Rrestoring Faith is correct to say 3 Strings are created but more than 3 objects are created
+ 2
this is right answer fella. only 3 object e using new and one when creating variable.
+ 2
i don't know what backing array you are talking about. String is created in String pool.
+ 2
I posted a link to the source code, behind the scenes a String has an array of characters, which is itself an object. Therefore any String object implicitly refers to an array object too
+ 1
Yes 3 String objects are created :)
0
(am i right?)
number of instances = 6
number of objects = 4
string is immutable
0
String s="hey";//object 1 and creates a backing array object 2
String s1="hey";//referring to object 1
String s2=new String("hey");//object 3 and creates a backing array object 4
String s3 =new String("hey");//object 5 and creates a backing array object 6
As previous answer said, in some cases the backing arrays might be the same reducing the number slightly