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

前端 未结 9 1163
慢半拍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:07

    String s1="Java";
    String s2="Java";
    My question is whether these two references point to the same memory location  
    

    Dumb citing §3.10.5 of Java Language Specification:

    A string literal is a reference to an instance of class String (§4.3.1, §4.3.3).

    Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

    And read the comments to code example there:

    This example illustrates six points:

    • Literal strings within the same class (§8) in the same package (§7) represent references to the same String object (§4.3.1).

    • Literal strings within different classes in the same package represent references to the same String object.

    • Literal strings within different classes in different packages likewise represent references to the same String object.

    • Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.

    • Strings computed by concatenation at run time are newly created and therefore distinct.

    • The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

提交回复
热议问题