Explanation of toString method output and difference between toString out and hashCode output

276 views Asked by At
public class ObjectClass {
    public static void main(String[] args) {
        Demo dm = new Demo();
        Object obj = dm.getObject();
        System.out.println("Class name :: "+obj.getClass());
        System.out.println("To String " + dm.toString());
        System.out.println("HashCode "+ dm.hashCode());
    }
}

Output

    Class name :: class newTopic.Object.Demo
    To String :: newTopic.Object.Demo@2a139a55
    HashCode :: 705927765

What is the difference between that Demo@2a139a55 and hascode 705927765

2

There are 2 answers

1
Eran On

If you look at the Javadoc of Object's toString(), you'll see that:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', andt he unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Hence dm.toString() returned:

newTopic.Object.Demo      @           2a139a55

getClass().getName()  +  '@'  + Integer.toHexString(   705927765   )
                                                     dm.hashCode()
3
Lokesh Sharma On

These two are Object class method. If you do not override, then these will be inherited automatically. Here I will try to explain 3 methods, toString(), equals() and HashCode().

  1. toString - It help to represent the object in form of String. (for more info - https://www.geeksforgeeks.org/object-tostring-method-in-java/ go through this link).

  2. equals and HashCode - equals method is used to compare the equality of two object and HashCode is helpful to generate hashCode of the object. Both together are helpful in HashMap (mostly). To get more information, please read about internal implementation of HashMap. https://www.geeksforgeeks.org/internal-working-of-hashmap-java/

I hope this would be helpful for you.