aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Need help to understand the diff bet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Need help to understand the diff bet "==" vs "equals()" method" Watch "Need help to understand the diff bet "==" vs "equals()" method" New topic
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: 2578

== 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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Need help to understand the diff bet "==" vs "equals()" method