toString( )

  • If we are trying to print the object, println method automatically called the toString method.
  • toString( ) method is predefined method inside the Object class.
  • Object class is the parent class of every class.
  • toString( ) method returns String representation of hash code.
    • packageName.className@hexaDecimalValueOfHashcode.

Ex 1:

public class Sample {

	public static void main(String[] args) {
		Sample sample_obj1 = new Sample();
		Sample sample_obj2 = new Sample();
		System.out.println("Print Sample Class Object1: " + sample_obj1);
		System.out.println("Print Sample Class Object2: " + sample_obj2);
	}	
}

OUTPUT:

Print Sample Class Object1: SelfLearn.Sample@c2e1f26
Print Sample Class Object2: SelfLearn.Sample@dcf3e99

Code Explanation:

  • Here, we are trying to print the sample class objects.
    • System.out.println(“Print Sample Class Object1: ” + sample_obj1);
  • Inside the println method calling area, we have passed Sample class object as an input.
  • Inside the println method defined area, toString method is called. (These are predefined).
  • Object class have toString method. Object class is the parent class of every class. So every class access it.
  • toString method returns the String representation of hashcode.

Ex 2:

public class Sample {

	public static void main(String[] args) {
		Sample sample_obj1 = new Sample();
		Sample sample_obj2 = new Sample();
		System.out.println("Print Sample Class Object1: " + sample_obj1);
		System.out.println("Print Sample Class Object2: " + sample_obj2);
	}	
	
	public String toString()
	{
		return "Hello";
	}
}

Output:

Print Sample Class Object1: Hello
Print Sample Class Object2: Hello

Code Explanation:

  • Sample class have it’s own toString method.
  • Here, Sample class toString method overrides it’s Parent class(Object Class) toString method.

Note:

  • hashCode method returns integer value of every object.
  • toString method returns String representation of hashCode.
    • packageName.className@hexaDecimalValueOfhashCode.
  • If we are trying to print object, println method automatically called the toString method.
  • Object class (Parent class of every class) provides the hashCode & toString method.
  • We can override the hashCode & toString method.

Leave a comment

Design a site like this with WordPress.com
Get started