Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String objects creation example  RSS feed

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am posting this question as I am always getting confused with its result so need a clarification on the following code.




So the simple question is how many objects would be created in Line 1 and Line 2 respectively.
I believe there would be 2 objects created in Line 1 in case "Rock" is already not present in the String pool. My Explanation for creating 2 objects:
1. One is in String Pool with value "Rock" which compiler identified at compile time and other using "new" in the heap.

Am I right or wrong?




 
Marshal
Posts: 59115
180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How many do you think?
Read this first.
 
Campbell Ritchie
Marshal
Posts: 59115
180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think you are correct, but look at the link first.
 
Rajat K Gupta
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks CR for the reply.
I read it but still had confusions.
The below code will give much clarity to the my understanding, so please check and do reply.




As per my understanding let me tell you no of objects created in Pool and Heap.
1. Line 1 ---> One object in Pool
2. Line 2 ---> One object in Pool
3. Line 3 ---> One object in Heap
4. Line 4 ---> One object in Heap
5. Line 5 ---> Two objects in Heap
6. Line 6 ---> One object in Heap
7. Line 7 ---> One object in Heap and One Object in Pool.

Is it ok?

 
Campbell Ritchie
Marshal
Posts: 59115
180
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You realise the string pool is part of the heap, so it is not quite accurate to distinguish heap and string pool like that.
Also the literal objects are created and put into the string pool when the class is loaded, so they actually exist before those likes are executed.
Aaprt fromthat I think you are correct; as yousay there are two objects both with the same content in 5. There are other objects created in 5, but I'll forget about them.
 
get schwifty. tiny ad:
Why should you try IntelliJ IDEA ?
https://coderanch.com/wiki/696337/IntelliJ-IDEA
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!