Following is the code snippet from a console application -
class MyClass
{
public int GetDay(string data22)
{
int returnValue = 0;
if (string.Compare(data22,"THURSDAY") == 0) // true
{
returnValue = (int)DayOfWeek.Thursday;
}
if (data22 == "THURSDAY") //false
{
returnValue = (int)DayOfWeek.Thursday;
}
if (string.Equals(data22, "THURSDAY"))//false
{
returnValue = (int)DayOfWeek.Thursday;
}
return returnValue;
}
}
class Program
{
static void Main(string[] args)
{
string ExecutionDay = "THURSDAY";
MyClass obj1 = new MyClass();
int MyDays = obj1.GetDay(ExecutionDay);
}
}
Question is - Why does the first comparison (string.compare) work and the other two comparison methods does not work in THIS PARTICULAR CASE ?
In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
equals() method and == operator is that one is a method, and the other is the operator. We can use == operators for reference comparison (address comparison) and . equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
Why does the first comparison (string.compare) work and the other two comparison methods does not work in THIS PARTICULAR CASE
There are invisible characters (particularly, a Left-to-Right mark (Thanks @MatthewWatson)) in your code. You can view them with any hex editor:
This is over-looked by string.Compare
, while it isn't with string.Equals
. You can see it in the docs:
Notes to Callers:
Character sets include ignorable characters. The Compare(String, String) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .NET Framework 4 or later, a culture-sensitive comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With