• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Number Of Objects in String

 
Ranch Hand
Posts: 643
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How many String objects are created when we run the following code.

String s1,s2,s3,s4;
s1 = "Hello";
s2 = s1;
s3 = s2 + "Pal";
s4 = s3;

Ans is 3
My ans is 2

According objects will be created as follows

s1=s2-->"Hello"
-->"Pal" (Lost)
s3=s4-->"HelloPal"

Does lost object "Pal" will count.
 
Ranch Hand
Posts: 107
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"creating an object" has nothing to do with "when the object will be eligible for GC" (I guess thats what you mean by "Lost"). So there will be 3 objects "created".


As an aside, the object having the string "Pal" is created in the string pool and hence it will be eligible for GC only when JVM unloads the class.
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, the object will count.

There will be 3 String objects created.
1: "Hello"
2: "Pal"
3: "HelloPal"
[ July 24, 2006: Message edited by: Harold Soppe ]
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Are string literals eligible for GC?
reply
    Bookmark Topic Watch Topic
  • New Topic