Showing posts with label Object class. Show all posts
Showing posts with label Object class. Show all posts

Sunday, 25 March 2012

How and Why to override the toString() method in Java

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a super class so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of toString() method. We will discuss why it is necessary to override toString method and how we can override it.

The toString() method in the Object class is used to display some information regarding any object.The toString method is widely implemented. It provides a simple, convenient mechanism for debugging classes during development.When debugging, you want to be able to print a human readable representation of your object.It is widely used for logging.
The toString() method of an object gets invoked automatically, when an object reference is passed in the System.out.println() method.



Wednesday, 21 March 2012

Overriding hashCode() method in Java or Why always override hashcode() if overriding equals()?

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a superclass so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of hashCode() method. We will discuss why it is necessary to override hashCode method,Why always override hashCode() if overriding equals() and how we can override them.

Default implementation of hashCode() in Object class

The signature of hashCode is:

public int hashCode()

How and Why to override the equals and hashCode methods in Java

Object class has following five non final methods.

1. clone()
2. equals(Object obj)
3. finalize()
4. hashCode()
5. toString()

Every Java class has Object as a superclass so by default all above methods are provided in every java class. In this article we will discuss in detail the concepts of equals() and hashCode() method. We will discuss why it is necessary to override these methods and how we can override them.

Default implementation of equals() in Object class

The default version of equals method present in the Object class has the same behavior as the == operator which in turn simply checks if two reference variables are referring the same objects.Consider x and y, two object references, then x.equals(y) comparing the memory addresses of the objects referenced by x and y (i.e. not the data of the objects).