Browse DevX
Sign up for e-mail newsletters from DevX

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



Building the Right Environment to Support AI, Machine Learning and Deep Learning

String Equality

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?

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.



Thanks for your registration, follow us on our social networks to keep up-to-date