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

余生颓废 提交于 2019-12-27 14:54:08

问题


This is a question that I got in an interview.

I've two strings defined as

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

My question is whether these two references point to the same memory location. In general, 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, without storing the string "Java" redundantly ? The hash codes of s1 and s2 are the same. But are hashcodes dependent directly on memory location of the object?


回答1:


The process of combining identical strings is called "interning", and has been done for many years by lots of language compilers, but not always. The answer to the question, especially as expanded by @GennadyVanin--Novosibirsk, depends on the language and the compiler implementation. For Java, all constant strings are interned, as required by the Java Language Specification. But that's only constant string expressions, and only when they're compiled at the same time. If you have two Java strings sufficiently separated in time and space (e.g., compiled into separate JAR files), they will not be the same object. Similarly, dynamically created Java strings (e.g., the output of various toString() methods) won't be interned unless the method specifically requests it via String.intern(). And yes, all uses of an interned string will share the same memory locations - that's a big part of why strings are interned in the first place.

As to other languages, that's a bigger question, but with all the information in these answers, I'm sure you can research it on the web. Suffice it to say that there is no universal agreement on how this ought to be done.




回答2:


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.




回答3:


When compiler optimizes your string literals, it sees that both s1 and s2 have same value and thus you need only one string object. It's safe because String is immutable in Java.

String s1="Java";
String s2="Java";
System.out.println(s1== s2);

This gives result true because s1 and s2 points to the same object.

String Pool is the mechanism that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.




回答4:


Example.

First example

String s1 = "FirstString";
String s2 = "FirstString";

 if(s1 == s2) {
   //This condition matched true because java don't make separate object for these two string. Both strings point to same reference.
 }

Second example

String s1= "FirstString";
String s2 = new String("FirstString");

if(s1.equals(s2)) {
  //This condition true because same content.
}

if(s1 == s2) {
  //This condition will be false because in this java allocate separate reference for both of them
}

Conclusion: Java check whether string exist or not. If we create the object of second string using new and have different content then its creates object and assign different reference and In case of If we don't create the object using new and have same content then its assign the same reference as first string contain.




回答5:


Adding to others: new keyword always forces to create a new object. If you declare like below:

String s1 = "some";
String s2 = "some";

Then using String Pooling mechanism, both references s1 and s2 will refer to the same String object with the value "some".




回答6:


When you have

String str1 = new String("BlaBla");  //In the heap!
String str2 = new String("BlaBla");  //In the heap!

then you're explicitly creating a String object through new operator (and constructor). In this case you'll have each object pointing to a different storage location.

But if you have:

String str1 = "BlaBla";        
String str2 = "BlaBla";

then you've implicit construction. Two strings literals share the same storage if they have the same values, this is because Java conserves the storage of the same strings! (Strings that have the same value)




回答7:


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

both points to same object. for more detail click here




回答8:


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




回答9:


YES, Andrew Hare was answer on stack overflow in this link https://stackoverflow.com/a/2486195/4835894.

Basically, a string intern pool allows a runtime to save memory by preserving immutable strings in a pool so that areas of the application can reuse instances of common strings instead of creating multiple instances of it.



来源:https://stackoverflow.com/questions/15805578/will-two-strings-with-same-content-be-stored-in-the-same-memory-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!