About toString() method
Summary: Java comes with two styles of converting object into string form. "toString() method Convert Object to String form" discusses using toString() method.
We discussed toString() method in String class to some extent. Let us go more detailed here. toString() of Object class converts only objects into string form (remember, valueOf() of String class converts both objects and data types into string form). Every Java class implicitly inherits this method as Object class is the super class of all Java classes. toString() method is overridden by many classes like java.lang.Integer and java.lang.Double etc.
The following programs uses toString() method to convert object to string.
public class ToString
public static void main(String args)
ToString ts1= new ToString();
System.out.println("String form of ts1: " + ts1.toString());
int k = 100;
Integer it1 = new Integer(k);
String str = it1.toString();
System.out.println("String form of it1: " + str);
ts1.toString() returns a string value of object ts1. As Integer class has overridden toString() method, the output is different. Wherever, it1 is required as a string, str can be used.
Some places where a Java object is required to convert into string.
1. To display any value in a TextField, it is required in string form. For example, to display integer value 50 in TextField, it is required to convert int 50 into string 50.
2. When command line arguments are passed, they are converted implicitly into string.
3. Any value to display in frame using drawString() method requires a string. Any object or data type to be displayed is to be converted into string. Like this many examples exist in Java, especially in AWT.