public String toString()
Returns a string representing the data in this sequence. A new String object is allocated and initialized to contain the character sequence currently represented by this object. This String is then returned. Subsequent changes to this sequence do not affect the contents of the String.
Program:
package com.candidjava;
class StringBufferToString
{
private int x, y;
public StringBufferToString(int x, int y)
{
this.x = x;
this.y = y;
}
public int getX()
{
return x;
}
public int getY()
{
return y;
}
}
public class ToStringDemo
{
public static void main(String args[])
{
StringBufferToString point = new StringBufferToString(10, 10);
// using the Default Object.toString() Method
System.out.println("Object toString() method : " + point);
// implicitly call toString() on object as part of string concatenation
StringBuffer sm = point + " testing";
System.out.println(sm);
}
}
Output:
Object toString() method : StringBufferToString@119c082
StringBufferToString@119c082 testing
Description:
Implementing toString method in java is done by overriding the Object?s toString method. The java toString() method is used when we need a string representation of an object. It is defined in Object class. This method can be overridden to customize the String representation of the Object. Below is a program showing the use of the Object?s Default toString java method.
Specified by:
toString in interface CharSequence
Returns:
a string representation of this sequence of characters.