• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

use of equals() method for SCJP 1.4

 
Ranch Hand
Posts: 208
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 279
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
reply
    Bookmark Topic Watch Topic
  • New Topic