Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Count the number of object

 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s = new String("Hi");
String s1 = new String("Hello");
String s2 = "Hi";

The total number of object are 4 . Right ?
2 object on string literal pool .
2 object on garbage collection heap .

s is a reference variable that is pointing to an object that is on GCH & that object is poining to an object of SLP that has string literal Hi

s1 is a reference variable that is pointing to an object that is on GCH & that object is poining to an object of SLP that has string literal Hello

s2 is a reference that is directly pointing to the same object of SLP that has string literal Hi

Am I Right in everything ???

thanks .
[ January 08, 2005: Message edited by: rathi ji ]
 
Rob Harris
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
s and s2 are not the same object, despite containing the same content, so that makes 5. If the line initialising s2 read
s2 = s;
then there would be 4.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that Rathi is correct, but I don't know how to test his answer without looking at the bytecode.
 
ankur rathi
Ranch Hand
Posts: 3830
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is final answer ???
 
Jay Pawar
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rathi,
Your explanation is absolutely correct. 4 objects.
[ January 08, 2005: Message edited by: Jay Pawar ]
 
Arjun Shastry
Ranch Hand
Posts: 1898
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If I run javap command,I see the term 'new' only twice.
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Arjun Shastry:
If I run javap command,I see the term 'new' only twice.



Do you expect more? String literal objects are not created with new.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic