• Post Reply Bookmark Topic Watch Topic
  • New Topic

How many objects are being created?  RSS feed

 
Damien Fergusson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Had a simple question around Stringz instance pooling

If I have a situation like this:
Scenario 1:


and then flipped
Scenario 2:


In each case- how many objects are being created in the String Pool and Heap ?
I assumed both would create an equal number of objects (2 Objects - one single "aaa" for both lines in each scenario in the String pool and one for the new Operator).
I was told in an iview that this wasn't correct - I'm curious as to what is wrong with my understanding?
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dont trust me, but string literals are stored in a different place. otherwise it is all the same
 
Damien Fergusson
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Randall Twede wrote:dont trust me, but string literals are stored in a different place. otherwise it is all the same


thats what I thought was well - apparently its not the case - I'm just hoping for someone to tell me why this is so!!
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Damien Fergusson wrote:Had a simple question around Stringz instance pooling

If I have a situation like this:
Scenario 1:



Line 1 creates zero objects.
Line 2 creates one String object on the heap and one char[] object on the heap (the String's backing array).

and then flipped
Scenario 2:


Line 1 creates one String object on the heap and one char[] object on the heap (the String's backing array).
Line 2 creates zero objects.

In each case- how many objects are being created in the String Pool and Heap ?


The String object "aaa" is created and placed into the constant pool when the class is loaded, if it wasn't there already from some other class. It already exists before we get to those lines. Executing String s = "aaa"; simply gets a reference to the String object that already exists in the pool and copies it into variable s.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!