0
String size difference according to initialization method
String s1 = new String("Jack"); String s2 = "Jack"; Is there a difference between the sizes of s1 and s2?
7 ответов
+ 7
Do you mean the size of the objects in memory?
What happens here is that you force the creation of a brand new String object. The new operator tells the jvm NOT to point to an equal String on the memory, but to absolutely create a new one even if the same String does already exist. You bypass the thing called string pool with that. Not a good idea.
On s2, you allow the jvm to reuse an already existing string. Saves memory from the second equal string you need onwards.
+ 5
Jack
When the string s2 is loaded from the string constants pool to the heap, it is stored there as a string object, so both string objects should have the same size then.
+ 5
Java hides the memory ;)
Main difference between C++ and Java.
If you are able to, pls post the quiz (upload screenshot to imgur or such and link it here).
+ 4
Thanks! For me this is kind of misleading in the best case... I'd report it if I came across the quiz. You might do so, if you agree.
Not all quizzes are correct or good, unfortunately.
Had one yesterday which wanted me to predict the order of elements in a HashMap o_O
Please, quiz raters: When in doubt: skip the quiz ;)
+ 1
I ment the actual size of the objects, the lengths should be equal.
Thanks for the explanation, but I still don't understand why the objects' sizes are different.
It shouldn't matter that the JVM created or not a new object, they should be the same size.
+ 1
Thanks Tashi N , I had a challenge question which asked that and the answer said they are differ by their sizes.
In C++ I would check sizes with sizeof function, but I couldn't find an easy way to do so on Java
0