• Post Reply Bookmark Topic Watch Topic
  • New Topic

how many objects are created ?  RSS feed

 
Ranch Hand
Posts: 227
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String s= new String ("Hello");
String a = new String ("Hello");

As per my understanding the first line creates 2 objects : 1 for the heap memory and 1 for String pool

2nd line : new object created and no new object created in the String pool as the keyword already exists in the pool.

So the total number of objects created after the execution of 2 lines are : 3

 
Ranch Hand
Posts: 236
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each line above generates a new String object.
Only intern() method on a string object moves to string pool.
 
Santosh Kumar Nayak
Ranch Hand
Posts: 227
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So you mean to say that for the 1st line only 1 object gets created ?
 
Rancher
Posts: 42975
76
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you think this is an important question to ask? The reason I ask is because a String object encapsulates several other objects, so if the purpose is to find out how many objects are allocated overall by those two lines of code, then the answer is: quite a few more than 2 or 3.
 
Marshal
Posts: 58449
178
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please tell us where such questions come from. Also please search this forum, because lots of people seem to ask the same question.
 
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Santosh Kumar Nayak wrote:As per my understanding the first line creates 2 objects : 1 for the heap memory and 1 for String pool


Which is also (almost certainly) in heap memory.

no new object created in the String pool as the keyword already exists in the pool.


<nitpick> it's not a keyword; it's a literal </nitpick>

Like Ulf, I wonder why you think this question is important; but that said, you might find the CachedObjects page worth reading.

Winston
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!