Wednesday 8 February 2017

Java toString() Method




toString() Method

 The toString() is a method that is defined in the java.lang.Object class. The method toString() is defined in the superclass named Object. It is used to represent (OR print) any object as a string. In general, the toString method returns a string that "textually represents" the object. The result should be a concise but informative representation that is easy for a person to read.
 toString() is used to represent any Java Object into a meaningful string representation. It provides a simple, convenient mechanism for debugging classes during development. It's also widely used for logging, and for passing informative error messages to Exception constructors and assertions.

 Understanding problem without toString() method:

Let's see the simple code that prints reference.

Student.java

 class Student
 {
  int id;
  String name;
  Student(int i,String n)
  {
   id = i;
   name = n;
  }
  public static void main(String args[])
  {
 &emsp ;Student s1 = new Student(111,"Karan");
   Student s2 = new Student(222,"Aryan");
   System.out.println(s1);//compiler writes here s1.toString()
   System.out.println(s2);//compiler writes here s2.toString()
  }
 }

The output generated by the above progrma
Student@3e25a5

Student@19821f

When a object is passed in print() method as an argument then compiler internally call toString() method on the object. It returns object representation as classname@hexadecimal representation of hash code of the object. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:

Student2.java

 class Student2
 {
  int id;
  String name;
  Student2(int i,String n)
  {
   id = i;
   name = n;
  }
  public String toString()//overriding the toString() method
  {
   return id+" "+name;
  }
  public static void main(String args[])
  {
   Student2 s1 = new Student2(111,"Karan");
   Student2 s2 = new Student2(222,"Aryan");
    System.out.println(s1);//compiler writes here s1.toString()
   System.out.println(s2);//compiler writes here s2.toString()
  }
 }

OUTPUT:
111 Karan
222 Aryan

 Next Topic Shahbaz

0 comments:

Post a Comment

Powered by Blogger.

Stats