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

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS