String s1,s2,s3,s4; String s1="hello"; String s2=s1; String s3 =s2+"pal"; String s4=s3; how many String object are created? answer is 3, why? ------------------ Jeff
Jeff
Pravin Panicker
Ranch Hand
Joined: Oct 05, 2000
Posts: 62
posted
0
Hi Jeff lets see 1.String s1="hello" creates String object "hello" on the heap with reference s1 to it.So 1 object in the heap.(1) 2.The second line assigns s2 reference to s1 ie to "hello" No objects are created here. 3.String s3 =s2+"pal"; Here "pal" is created(2). Since Strings are immutable, s2+"pal" returns a new String object "hellopal"(3).So Object number 3 in the heap 4.This does nothing except for assigning a new reference to s3. So there are 3 objects created .Since "pal" has no reference after line 3,It'll be eligible for garbage Collection. ------------------ Pravin R Panicker Sun Certified Java Programmer
Pravin R Panicker<br />SCJP,SCWCD
Shaibaz Gadhwala
Greenhorn
Joined: Jan 22, 2001
Posts: 11
posted
0
Hello, I've tried the following piece of code to the point raised by you and I think there are only two strings that are created. I dont think so there is a third one present.
class T { public static void main(String args[]) { String s1="hello"; String s2=s1; String s3 =s2+"pal"; String s4=s3;
System.out.println(s1==s2); System.out.println(s3==s4); } } o/p true true Awaiting Reply.... Sorry for the above piece of information... I think Pravin has got a valid point here....
[This message has been edited by Shaibaz Gadhwala (edited February 15, 2001).]
Jeff Sky
Greenhorn
Joined: Feb 15, 2001
Posts: 9
posted
0
Hi, thanks, I got it!
Jeff Sky
Greenhorn
Joined: Feb 15, 2001
Posts: 9
posted
0
1. String s1 = "She was dancing widdershins"; 2. String s2 = s1; 3. s1 += "upon the shore"; 4. if (s1.equals(s2)) 5. System.out.println("They match"); 6. else System.out.println("not match"); wish it help to understand the String object!
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.