toString() Java

toString() Java

Generally, a programmer knows toString() method is used to convert an object into string form. But toString() has big story to know.

Some known facts of toString() method

1. toString() method is defined in java.lang.Object class.
2. As it is defined in Object class, every class of Java inherits this method. For this reason, any object of Java can use this method to convert into String.
3. toString() is overridden by some sub classes in the way they want. Even you also can do it. We see it in the coming program.
4. Every System.out.println() calls toString() method internally.

Following is the method signature as defined in Object class and what Sun documentation says:

public String toString()
Returns a string representation of the object. In general, the toString method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Before going further, let us know the answer to the following question.

Why the following three objects give different results when printed?

Now the question is why d1 prints quite a different result where as i1 and today print 10 and system date and not with @ symbol combination. The answer is these two classes Integer and Date override the toString() method of Object class and prints their own style of result.

Every System.out.println() method calls implicitly toString() method. See the code.

For the following code

String x = “ram”; int y=786; char z =’c’;
String s = x + y + z;

JVM does the following implementation

String s = new StringBuffer().append(x).append(y).append(z).toString();

or to say

System.out.println(new StringBuffer( ).append(x).append(y).append(z).toString());

What is happening?

Statement 1: An empty string buffer is constructed.
Statement 2: Each argument(may be any data type) in turn is concatenated to the string buffer, using its append( ) method.
Statement 3: The string buffer is converted to a string by calling toString() method.

Then another question is, can we override in our own class to print our own style of output. Yes, you can. See the following code.

By the above explanation, you understood that every System.out.prinltn() calls toString() method. Keeping this in view, let us override toString() in our own close in our own way.

For the above code just add (or override) toString() method as in the following code.

toString() Java

As in the above code, you can override the toString() in the way you require. Integer and Date classes has done this way only in their code.

2 thoughts on “toString() Java

  1. Mahi

    Public Class Date
    public static void main(String args[])
    Date today = new Date();
    why output printing with @ symbol ? And same with integer

Leave a Reply

Your email address will not be published. Required fields are marked *