I have a simple recursive method written in both Java and C#
Java
public static String reverse(String letter) {
if (letter == "")
return "";
else
return letter.substring(letter.length() - 1)
+ reverse(letter.substring(0, letter.length() - 1));
}
C#
public static string reverse(string letter)
{
if (letter == "")
return "";
else
return letter[letter.Length - 1]
+ reverse(letter.Substring(0, letter.Length - 1));
}
But the Java version fails at letter == "", it returns false even if the letter is empty. Why does the C# version work while the Java version fails?
In both C# and Java, the
==operator checks for reference equality by default.However, in .NET, the
==operator is overloaded for thestringtype to check for value equality instead:Another factor you need to take into account when using both languages is string interning, which can cause even reference equality to succeed for strings that might appear distinct. From MSDN (for C#):
String interning is applied across both Java and C#, and typically gives consistent results. For example, both languages evaluate string concatenation at compile-time, meaning that
"a" + "b"is stored as"ab":However, when getting a zero-length substring, only C# returns the interned empty string: