Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of equals() method for SCJP 1.4

 
Jay Ashar
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all... I am bit confused on equals method I thought it takes only variables with object references...
Integer L = new Integer(5);
Integer K = new Integer(5);
if ( L.equals(K)){ // This works fine since both are objects....
String H = "Hello";
if (H.equals("Hello"){ //This works fine too...??
Shouldnt the second if statement fail since it is not using any objects in equals method input param. I am confused.
 
Alfred Kemety
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, 2 points needs to be cleared here.
1- Since all classes extends implicitly or explicitly, directly or indirectly the Object class, they all inherit the equals() method, and either they override it (like String) or just use it (like StringBuffer).
2- "any string" creats an object of type String and returns a reference.
So S1.equals("hello") is actually comparing 2 Strings one with a reference called S1 and the other has a reference with no name. it uses the String class implementation of the equals() method which also accepts objects of type Object, thus it returns true.
HTH
[ October 15, 2002: Message edited by: Alfred Kemety ]
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please read the following article which provides extensive information about how to use the equals() method:
Equals And Hash Code by Manish Hatwalne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic