DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

hashCode(),toString() and clone()

What is hashcode()?

  • hashCode() provides a numeric representation of an object for faster searching in hash-based collections.
  • If two objects are equal, they must return the same hash code, but the reverse is not always true.

What is toString()?

  • toString() is a method in the Object class (the root class of all Java classes).
  • Its purpose is to return a string representation of an object.
  • When you print an object (using System.out.println(object)), Java internally calls that object’s toString() method.
  • Default toString() → className + "@" + hashcode.
  • We override it to provide meaningful output of object state.
  • Often used in debugging, logging, and printing objects.

What is clone()?

  • clone() is a method in the Object class that is used to create a copy of an object.
  • The new object will have the same values as the original object.
  • To use clone(), a class must implement the Cloneable interface; otherwise, it throws CloneNotSupportedException.

Types of Cloning:

  • Shallow Copy (default clone):
  • Copies object’s fields as they are.
  • If the object contains references to other objects, only the references are copied (not the actual objects).
  • Deep Copy (custom clone):
  • Copies not only the object but also the objects it refers to.
  • Requires overriding clone() or using serialization.

Top comments (0)