will two strings with same content be stored in the same memory location?

前端 未结 9 1153
慢半拍i
慢半拍i 2020-11-27 19:29

This is a question that I got in an interview.

I\'ve two strings defined as

String s1=\"Java\";
String s2=\"Java\";

My question i

9条回答
  •  遥遥无期
    2020-11-27 20:09

    String s1="Java";
    String s2="Java"; 
    

    Do they point to the same memory location?

    I originally said "no" but in the case above, see the StringPool answer referred to below, it's actually yes..

    "when we create identical strings (without new keyword), does the content get stored in the memory only once and all the String objects with the same content just refer to the same location"

    ...kind of see detailed answer in question "Java Strings and StringPool"

    "The hash codes of s1 and s2 are the same. But are hashcodes dependent directly on memory location of the object?"

    No the hashcodes depend on the content of the String

提交回复
热议问题