Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are equal java strings taking the same address? [duplicate]

Tags:

java

string

javac

Possible Duplicate:
String object creation using new and its comparison with intern method

I was playing around with Strings to understand them more and I noticed something that I can't explain :

String str1 = "whatever";
String str2 = str1;
String str3 = "whatever";
System.out.println(str1==str2); //prints true...that's normal, they point to the same object
System.out.println(str1==str3); //gives true..how's that possible ?

How is the last line giving true ? this means that both str1 and str3 have the same address in memory.

Is this a compiler optimization that was smart enough to detect that both string literals are the same ("whatever") and thus assigned str1 and str3 to the same object ? Or am I missing something in the underlying mechanics of strings ?

like image 276
MohamedEzz Avatar asked Nov 19 '12 08:11

MohamedEzz


2 Answers

Because Java has a pool of unique interned instances, and that String literals are stored in this pool. This means that the first "whatever" string literal is exactly the same String object as the third "whatever" literal.

As the Document Says:

public String intern()

Returns a canonical representation for the string object. A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

All literal strings and string-valued constant expressions are interned. String literals are defined in §3.10.5 of the Java Language Specification

Returns: a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.


like image 132
Parth Soni Avatar answered Sep 28 '22 19:09

Parth Soni


http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3

As the post says:

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool.

like image 35
Felipe Fernández Avatar answered Sep 28 '22 18:09

Felipe Fernández