Using == or equals() for string comparison
by, 11-08-2011 at 06:34 PM (402 Views)
Mostly new Java programmers get confused when comparing strings. You can check the equality of strings either by using "==" or "equals()". But one should know when to use each of these in order to get the required results.
First, lets talk about "equals() " method. Method "equals()" is included in the class java.lang.Object which every Java class inherit. "equals()" method actually compares the characters that make up String object. It actually creates two char arrays and puts the characters of each String objects in separate array and then performs the comparison.
The "==" operator compares two object references to see whether they refer to the same instance. It checks whether two objects are exactly the same object or not. Two strings may be different objects, but can have the same value (have exactly the same characters in them). In such case, "==" will return false.Java Code:String str_Obj1 = "Hello"; String str_Obj2 = "Hello";System.out.println((str_Obj1.equals(str_Obj2))); //prints true as str_Obj1 and str_Obj2 have the same string i.e Hello
Take special care when comparing objects. If you wish to see whether two objects are same or not, then use"==" to, or use equal() to see if they have the same value. Sometimes errors caused by such mistakes are hard to find. So take special care.Java Code:String str_Obj1 = new String("Hello1"); String str_Obj2 = new String("Hello1");String str_Obj3 = str_Obj1; // assigning str_Obj1 to str_Obj3 System.out.println("String 1 is " + str_Obj1); // prints Hello1 System.out.println("String 2 is " + str_Obj2); // prints Hello1 System.out.println("String 3 is " + str_Obj3); // prints Hello1 System.out.println(str_Obj3 == str_Obj1); // returns true as str_Obj3 and str_Obj1 refer to same object System.out.println(str_Obj3 == str_Obj2); // returns false as str_Obj3 and str_Obj2 refer to different object // although have same values stored