Help coderanch get a
new server
by contributing to the fundraiser
  • 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
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

how many objects will create

 
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
String s1="hello";
String s2="hello";
String s3 = new String("hello");
how many objects will create?
 
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
well!!!i think here 3 string objects S1 ,S2 ,S3 will be created....
as though we can say three string references S1,S2,S3 will be created.....
i hope it helps..............
 
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think there is only one string object, because they are stored differently, and the actual strings are reused, I forget what is is called, but i believe it is part of the reason why string are immutable.

So I think one String object in memory with 3 references.

I do believe that during compilation it probably creates something like 4 String objects as I was always told to create String with literals rather then new, because (in this example) the new commands creates a String and then a String object is created for the string liternal.

At least thats my vague understanding of it all.

hope it helps
G
 
Marshal
Posts: 79630
380
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This question comes up about once a month.

There are three "hello" literals, which are identical, so that is one object.
There are two Strings set up to be equal to that object, so we still have one.

There is a "new String" in the 3rd line, which makes 2 Strings.

There are probably quiet a lot of other objects in the background which we don't notice.

Try
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic