*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes How many String object created? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "How many String object created?" Watch "How many String object created?" New topic
Author

How many String object created?

Jeff Sky
Greenhorn

Joined: Feb 15, 2001
Posts: 9
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
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
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
Hi, thanks, I got it!
Jeff Sky
Greenhorn

Joined: Feb 15, 2001
Posts: 9

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://aspose.com/file-tools
 
subject: How many String object created?
 
Similar Threads
please help me
String Object
String Objects
String Objects
question...