Monday 24 March 2014

toString : Return String representation of the object

public String toString()
Returns a string representation of the object. The default implementatin looks like below.

   public String toString() {
      return getClass().getName() + "@" + Integer.toHexString(hashCode());
   }

By default, toString method returns a string consisting of the name of the class of which the object is an instance, the at-sign character @, and the unsigned hexadecimal representation of the hash code of the object.

class Box{
 int width, height;

 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
 public static void main(String args[]){
  Box b1 = new Box(10, 20);
  System.out.println(b1);
 } 
}

Output
Box@5c09036e

When you call an object in println method, by default it calls the toString method of the particular object.

You can override the toString method to print custom message for an object. It is recommended that all subclasses override this method.

class Box{
 int width, height;

 Box(int width, int height){
  this.width = width;
  this.height = height;
 }
 
 public String toString(){
  return "Box has width = " + width + " and height = " + height; 
 }
 
 public static void main(String args[]){
  Box b1 = new Box(10, 20);
  System.out.println(b1);
 } 
}

Output
Box has width = 10 and height = 20

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment