Thursday, 2 February 2017

toString() METHOD IN JAVA

To represent any object in the form of string, we use toString() method. Suppose if we print the object first then it will generate the hashcode of that particular object. So to generate user specific code we need to override toString() method. Using toString() method we can return the value of the object and we don’t have to write long code to fetch its values.

Example –
public class Reuse {
          String name;
          int rollno
          public Reuse(String name, int rollno) {
                   super();
                   this.name = name;
                   this.rollno = rollno;
          }
          public static void main(String[] args) {
                   Reuse r1 = new Reuse("abc", 101);
                   Reuse r2 = new Reuse("xyz", 111);
                   System.out.println(r1);
                   System.out.println(r2);                
          }
}

Output –
string.Reuse@15db9742
string.Reuse@6d06d69c

Example –
public class Reuse {
          String name;
          int rollno
          public Reuse(String name, int rollno) {
                   super();
                   this.name = name;
                   this.rollno = rollno;
          }       
          @Override
          public String toString() {
                   return "name=" + name + ", rollno=" + rollno;
          }
          public static void main(String[] args) {
                   Reuse r1 = new Reuse("abc", 101);
                   Reuse r2 = new Reuse("xyz", 111);
                   System.out.println(r1);
                   System.out.println(r2);                
          }
}

Output –
name=abc, rollno=101
name=xyz, rollno=111


Note – After overriding the toString() method we can the user defined output.

No comments:

Post a Comment