Overriding toString() method in JAVA

The toString() method returns the string representation that describes the object.
Consider the following java program :
---------------------------------------
class Demo001
{
String name;
 public Demo001(String name)
{
      this.name= name;
 }
}

class Demo001Test
{
public static void main(String[] args)
{
     Demo001 d1 = new Demo001("Ravi");
     System.out.println("Demo001 : "+d1);
     System.out.println("Demo001.toString() : "+d1.toString());
}
}
----------------------------------------
When we run it, we get a output similar to this :

 

This is not what we expected. We should be getting some valuable information from the object. This can be done by overridding toString() method.

Example :
----------------------------------------

class Demo002
{
String name;
public Demo002(String name)
{
this.name = name;
}

public String toString()
{
return name;
}

}
class Demo002Test
{
public static void main(String[] args)
{
Demo002 d2 = new Demo002("Ravi");
System.out.println(d2);
System.out.println(d2.toString());

Integer i = 10;
System.out.println("Value of Integer Object : " +i);
System.out.println("Value of Integer Object using toString() method : " +i.toString());

}

}
--------------------------
Lets have a look at the output :


Now we are able to get some valuable information. For the predefined Object classes like Integer, Float, Byte etc, the toString() method is already overridden.

We can thus use the toString method to return some valuable information about the object we created.!

Comments

Popular posts from this blog

Writing your own ejabberd Module

npm ECONNREFUSED error

Conditional Flow - Spring Batch Part 6