Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How many String object created?

 
Jeff Sky
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Pravin Panicker
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Shaibaz Gadhwala
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, thanks, I got it!
 
Jeff Sky
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic