Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Need help to understand the diff bet "==" vs "equals()" method

 
Karthik Balasubramanian
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2596
Android Firefox Browser Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== 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
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Manish. Now I have a clear understanding.
Thanks
Karthik
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic