Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

how many objects will create  RSS feed

 
T sandya
Ranch Hand
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
String s1="hello";
String s2="hello";
String s3 = new String("hello");
how many objects will create?
 
dhwani mathur
Ranch Hand
Posts: 621
  • Mark post as helpful
  • send pies
  • 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..............
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • 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
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!