Thursday, December 23, 2010

Relation between toString() and hashCode() methods...

If you are a java programmer you need to have the clear picture of the java.lang.Object class, this Object class has the most important methods like toString() and hashCode() method. now you will be scratching your head what is the relation between toString() and hashCode() methods.
the Answer is as follows.
  • The Signature of the hashCode method is as follows.
                public native int hashCode();

 the hashCode method is a native method  which returns the integer value.
  • The Signature of the toString() method is as follows.
     public String toString() 
      { 
return getClass().getName() + "@" +Integer.toHexString(hashCode());
       }


 so the toString() methods internally uses hashCode() Method.

Actually
                                 System.out.println(reference);
                                            is equivalent to
                                 System.out.println(reference.toString());


the example for the above concepts is as follows..

Example-1

//MyDemo.java

public class MyDemo
{
public String toString()
{
return "secret";
}
public static void main(String ar[])
{
MyDemo m=new MyDemo();
System.out.println(m);
System.out.println(m.toString());
}
}

Output is...
secret
secret
***************************************************************

Example-2
//MyDemo.java

public class MyDemo
{
public int hashCode()
{
return 1;
}

public String toString()
{
return "secret";
}
public static void main(String ar[])
{
MyDemo m=new MyDemo();
System.out.println(m);

}

}
Output is..
secret


because the toString() method internally uses hashCode() method only in Object class.
right now we are not calling the hashCode() function.

that is why we will get only secret as a output












 

2 comments:

  1. What is the exact use of hashCode() function.
    When exactly we should override.

    ReplyDelete
  2. when ever the user creates the Object of a class the JVM will create the Object of your class in Heap and it will generate a unique Hexa Decimal number so that the object of your class will be uniquely identified by the every one. To store the Objects the local operating System maintains a Hash type of functionality so that is why the name is hashCode.
    That is why it is highly recommended that you should override the toSting() and hashCode() method in every Enterprise applications like EJB.
    so Ultimately if you override the toString() and hashCode() method the actual address of the User Created object will be kept Secret.


    that is why you might override the toString() and hashCode() method in most of the enterprise applications.

    ReplyDelete