Tag Archives: equals

Avoid comparing strings with == in Java

While beginning development in Java, especially if coming from a .NET background (but not necessarily) you might do string comparison with == in Java. Don’t do it. It will compare the string instances and not their effective value.
You might even try it first to check if == really works, testing it in a wrong manner like so :

public static void main(String[] args) {

    String s1 = "Abc";
    String s2 = "Abc";

    System.out.println("s1 == s2 -> " + (s1 == s2));
}

This will output

s1 == s2 -> true

.. which might lead you to believe this works. This does return the correct value because of a feature present in Java and .NET called string interning (not specific to Java or .NET).

Try to obtain a string instance dynamically like concatenating two existing instances and see how things don’t work anymore :

public static void main(String[] args) {

    String s1 = "Abc";
    String s2 = "Abc";

    // new lines :
    String capitalA = "A";
    String bc = "bc";
    String s3 = capitalA + bc;

    System.out.println("s1 == s2 -> " + (s1 == s2));
    // new line :
    System.out.println("s1 == s3 -> " + (s1 == s3));
}
s1 == s2 -> true
s1 == s3 -> false

Weird, huh? That’s because at compile time there are four distinct strings generated : “Abc” (once, even if referred twice), “A” and “bc”. The “Abc” instance obtained by joining “A” and “bc” will be generated at runtime and, of course, it will be a different instance than the first “Abc” instance. That’s why the result of the == operator comparison will be false.
Read more »

Back to basics – object equality

What do you think this piece of code will output?

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(GetValue() == (object)true);
            Console.WriteLine(object.Equals(GetValue(), true));
        }

        static object GetValue()
        {
            return true;
        }
    }

I won’t be like others and ask you not to run the code. Run the code if you feel like it. I’ll wait here.

Back already? Surprised?
I surely have been.. I’ve found a piece of code similar to this as I was cleaning up code in our repository. You have a method that is required to return object (as in System.Object) and you want to check if, unboxed, it holds the value of true (or not).

Why exactly does

    GetValue() == (object)true

return false considering that GetValue() returns always a true value? Well… because you are comparing two instances of a System.Object and the ‘==’ operator is coded in a way that uses the ReferenceEquals (and not Equals) method on System.Object.

The author could have unboxed it to a local variable and do the check after but the speed of coding is so much important for some of us.. Thank you ReSharper for pointing this to us and fixing a potentially subtle bug.