the Answer is as follows.
- The Signature of the hashCode method is as follows.
the hashCode method is a native method which returns the integer value.
- The Signature of the toString() method is as follows.
{
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());
}
}
{
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);
}
}
{
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
What is the exact use of hashCode() function.
ReplyDeleteWhen exactly we should override.
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.
ReplyDeleteThat 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.