Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java Language
Expertise: Beginner
Nov 13, 2000

String Equality

Question:
When you compare two objects through the "== operator," Java checks for reference equality. For example, if you create two String objects with "new" keywords and initialize them with same value and compare them with if(s1==s2), it returns false because the references are not same. But if you initialize two Strings to the same inline string value (String s1 = "s", s2 = "s";) the same test returns true. Why is this?

Answer:
Java aggressively attempts to optimize the memory used by strings. At compile time, the compiler will coalesce any strings that share the same value into a single reference. That is why the second case you present results in the two String references being equal.

However, at runtime, the JVM also attempts to coalesce strings. The fact that your first case didn't prove equal is reflective of the implementation of the compiler and JVM you used, not of a general behavior you can rely on. It is also possible to programmatically coalesce strings, using the intern() method of the String class. This method always returns a reference to the same String reference for all Strings with the same value. The String class stores a static pool of strings that are reused in an attempt to conserve memory.

When you call "intern()," if the String's value is not already present in the pool, the String is added to the pool. In fact, when the compiler encounters constant and literal strings, it generates byte-code that includes a call to "intern()."

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap