| Author |
Need help to understand the diff bet "==" vs "equals()" method
|
Karthik Balasubramanian
Ranch Hand
Joined: Dec 13, 2002
Posts: 43
|
|
1.String s1="abc"+"def"; 2.String s2=new String (s1); 3.if (s1==s2) 4. System.out.println("== succeeded"); 5.if (s1.equals(s2)) 6. System.out.println(".equals() succeeded"); For the above question...the answer is Line 6 executes and Line 4 does not. I do not understand where I can use "==" operator...where I should use "equals()" method? Please help me out by saying how this works? Thanks Karthik
|
 |
Manish Hatwalne
Ranch Hand
Joined: Sep 22, 2001
Posts: 2573
|
|
== checks whether two referrences are referring to the *same object* on the heap, whereas the equals method (if implemented correctly) checks if the contents of two objects are *logically equal* or not. See if this example helps - Integer a = new Integer(7); Integer b = new Integer(7); Integer x = new Integer(1); Integer y = x; Here - a == b --> returns false; a.equals(b) --> returns true; AND x == y --> returns true; x.equals(y) --> returns true; HTH, - Manish
|
 |
Karthik Balasubramanian
Ranch Hand
Joined: Dec 13, 2002
Posts: 43
|
|
Thanks Manish. Now I have a clear understanding. Thanks Karthik
|
 |
 |
|
|
subject: Need help to understand the diff bet "==" vs "equals()" method
|
|
|