Two strings are created. Actually java forms a pool of literal strings whenever a new string object is created. So every time, it has to form a new string object, it first checks its pool of literal strings. If the same string exists in the pool, it refers to the same string. In our case, a string object is created for s1. No string object is created for s2, as it refers to same object s1. Since, strings are immutable another string object is created for s3. No string object is created for s4, as said above. The things would be different, if we say String s2 = new String(s1) In this case, another string object is created in the programmers space at compile time. (At run it checks for the existing pool of literal strings.) The string object in programmers space can be placed by calling the method intern() of the String class.
Sujit Kurtadikar
Ranch Hand
Joined: Dec 05, 2000
Posts: 68
posted
0
3 Objects will be created when the given program is executed. They are, "Hello" , "Pal" and "Hello Pal" s2 =s1 will not create new object, but will refere to same object refered by s1 (and Object ref count of "Hello" will become 2) s3 = s2+"Pal" -> first Object "Pal" will be created and then new Object "Hello Pal" will be created. s4 = s3 will refer to same object refered by s3. In this way 3 objects will be created. object "Pal" is temporarily created, it will become eligible for Grarbage Collection after object "Hello Pal" is created. Hope this will help you.
Anshuman Acharya
Ranch Hand
Joined: Jan 19, 2001
Posts: 144
posted
0
sujit is right... i made the same mistake as you deepak!
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.