Showing posts with label Overriding toString(). Show all posts
Showing posts with label Overriding toString(). Show all posts

Overriding toString() method in java

Object class toString() method will call internally by default whenever we print object reference even though object contains content.


public class StudentRecord {
       public static void main(String[] args) {
              Student s1=new Student(10);
              System.out.println(s1); //output : Student@1db9742           
       }
}

class Student{
       int id;
       Student(int id){
              this.id=id;
       }     
}


We got the output:  Student@1db9742 even we passed id=10
Whenever object class toString() called, internally it call hashCode()
Internal code of toString()
  
  public String toString()
  {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
  }

toString() return output as
Class name @ hexadecimal hashcode

If we override toString() method in our class then toString() method don’t call hashcode() method.


public class StudentRecord {
       public static void main(String[] args) {
              Student s1=new Student(10);
              System.out.println(s1); //output : Student id : 10           
       }
}

class Student{
       int id;
       Student(int id){
              this.id=id;
       }
       @Override
       public String toString() {       
              return "Student id : "+id;
       }
}


Whenever we override toString() method in our class it returns exact content of object (meaningful representation).
Above program gives output as:  Student id : 10

Note: String class overridden toString() method and it give meaningful representation by default

Example:

public class Test {
  public static void main(String[] args) {
        String s1=new String("hello world");   
        System.out.println(s1);// hello world
 }
}



In this program we doesn’t override toString() method any where even though it given exact output because we taken String class.