String Equality

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 thepool, 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().”

See also  Does It Make Sense to Splurge on a Laptop?

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist