Forums Register Login

String in VM string-pool

+Pie Number of slices to send: Send
[From javacoding.net mock exam] :
How many Strings are in the VM string-pool after executing this code fragment :

The answer is 2.
Could anybody explain this ?
I though that in the case above, only 1 string literal is store in the VM string-pool.
+Pie Number of slices to send: Send
Well you know that if 2 String references have the same string value at compile time due to the use of a String "literal" if you can call it so, then they both share the same String object, they both point to the same String, this happens in the first 2 lines of code.
In the third line, you instruct the compiler to construct a "new" object of type String with a value - maybe equal to another existing string in the string pool - and assign the reference to a String variable.
String S3 = new String("The same existing String")
result is 2 string objects.
HTH
+Pie Number of slices to send: Send
At last week's New England Java Users' Group, Joshua Bloch said that there never should have been a String(String s) copy constructor. Since strings are immutable there is no reason ever to make a copy of one.
+Pie Number of slices to send: Send
You ridiculous clown, did you think you could get away with it? This is my favorite tiny ad!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 682 times.
Similar Threads
need help for a question
Help on this Question
Initialization
String in VM pool?
string constant pool
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 22:51:31.