Question

This is a Java and C# question. We all know that, Object Identity(==) tests whether two objects refer to the same location and Obejct Equality(Equals method) tests whether two different (non identical)objects have the same value .But In case of string object Object Identity and Object Equality are same. For e.g Below two boolean expressions in if statements return true

string a="123";
string b="123";
if(a==b)
if(a.Equals(b))

Why is it so?? What is the rational behind this design decision?

Was it helpful?

Solution

Java and C# both use a memory-saving technique called string interning. Because strings are immutable in these languages, they can pool frequently-used strings (included hard-coded string literals, like in your example) and use multiple references to that one string in memory to save space.

OTHER TIPS

As far as I know, in .net the == Operator for Strings is overloaded to use Equals() instead of object identity. See this explanation for details: http://www.dotnetperls.com/string-equals

For if you need to know if it's really the same object, use this:

Object.ReferenceEquals(string1, string2)

Actually, at least in Java, there is a caching mechanism on strings. A pitfall is that two strings that are equal will sometimes, but not always return true when applying the identity operator. the following code prints false:

String a="123";
String b="12";
b=b+"3";
System.out.println(a==b);

If you really want to make sure, that a.equals(b) == true but (a==b) == false evaluates to false for two String a and b, then you can use the completely undervalued (^^) String constructor:

String a = new String("abc");
String b = new String("abc");
if (a.equals(b)) {
   doTheyAreEqual();
   if (a != b) {
     doButNotTheSame();
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top