Wednesday, May 6, 2009

.equals Vs == in Java

Recently a Java developer asked for help in a J2EE application. He was stuck in a bug for the past two days. The development environment was Windows, Eclipse IDE and Tomcat server. He was using old mill fashion of debugging by adding System.out.println in his code. Before anything else I asked him to setup debugger in Eclipse. The debugger made his life easy and helped him quickly figure out the problem area. But he couldn't understand why a particular if condition not behaving correctly. As you can guess from the title of this blog, it was the same age old problem of == and .equals().

In Java == is used to compare variables of primitive data types (byte, short, int, long, float, double, boolean, char). If == is used to compare two objects then it compares the object reference and not the values. An object in Java stores the memory reference where the object data is stored. In order to compare the values you need to use object1.equals(object2). Lets learn the difference with simple example -

String s1 = new String("test");
String s2 = new String("test");

Here we have defined two String objects s1 and s2. Value of both the variable is same "test", so we expect the variables to be equal.

if (s1 == s2) {
  System.out.println("Strings are equal");
} else {
  System.out.println("Strings are not equal");
}

Surprised to see that it prints "Strings are not equal". Well its correct as both s1 and s2 are referring to two different memory references.

if (s1.equals(s2)) {
  System.out.println("Strings are equal");
} else {
  System.out.println("Strings are not equal");
}

The above code is correct way of comparing String values. This code will print "Strings are equal". Now consider this below code -

String s1 = "test";
String s2 = "test";

if (s1 == s2) {
  System.out.println("Strings are equal");
} else {
  System.out.println("Strings are not equal");
}

Another surprise, it prints "Strings are equal". Its because Java compiler does the optimization. Notice the way s1 and s2 are defined. In earlier code we used new String("test") which makes sure new object gets created. But in this code compiler uses the same reference to define the two variables.

== and .equals() usage holds true for objects of any class. Remember every Java class implicitly extends Object class. Most of the Java core classes like Integer, Long, Double, Boolean, etc have .equals() method implemented. For your own class don't forget to implement the .equals() otherwise .equals() will behave same as ==.

No comments:

Post a Comment