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

how many objects  RSS feed

 
Mary Wallace
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when i say new String("hello") , how many objects are created. i think its only one . but my friend saying it will create two objects.

please correct me if im wrong
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"hello" is an instance of String, and you create a String with the new operator.

Consider this example.



The bytecode for this class is


[ March 12, 2007: Message edited by: Keith Lynn ]
 
fred rosenberger
lowercase baba
Bartender
Posts: 12541
48
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strings are special cases, because of the string pool.

Personally, i'd say you cannot answer the quesions as stated. if the literal "hello" was already used elsewhere in your program, then this specific line would create one object.

However, if "hello" has NOT been used anywhere else already, then you get two - one in the String pool and one from the "new" operator.

So, you are both right (or wrong).
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wouldn't the answer in any case be dependent on the class libraries? If Sun decided to fiddle around with the internals of the String class in the next release, there could well be 27 objects created.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!