views:

277

answers:

3

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?

+3  A: 

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.

Adam Maras
+1  A: 

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);
Buhb
A: 

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();
   }
}
Andreas_D