toString() Java

May 18, 2013 | Java General
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?

Demo d1 = new Demo();               //  Demo is a class
d1.x = 10;                          // x is a variable of Demo class
System.out.println(d1);             // prints something like Demo@42719c

Integer i1 = new Integer(10);  
System.out.println(i1);             // prints 10

Date today = new Date();  
System.out.println(today);          // prints system today date

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; System.out.println(s);

JVM does the following implementation

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

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.

public class Student
{
  String name; 
  int marks;

  public static void main(String args[])
  {
    Student std1 = new Student();
    std1.name = "S N Rao";  std1.marks = 55;
    System.out.println(std1);		          // it printed me Student@30c221

    Student std2 = new Student();
    std2.name = "Jyostna";  std2.marks = 65;
    System.out.println(std2);                     // it printed me Student@119298d
  }
}

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

public class Student
{
  String name; 
  int marks;

  public static void main(String args[])
  {
    Student std1 = new Student();
    std1.name = "S N Rao";  std1.marks = 55;
    System.out.println(std1);		

    Student std2 = new Student();
    std2.name = "Jyostna";  std2.marks = 65;
    System.out.println(std2);           
  }
  public String toString()
  {
    return "Student name: " + name + " and Student marks: " + marks;
  }
}

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.

toString() is overloaded 3 times in Integer class as follows.

1. public static java.lang.String toString(); 2. public static java.lang.String toString(int); 3. public static java.lang.String toString(int, int);

The first one is used to convert Integer object into string, the second one is used to convert int primitive data type into string and the third is used to convert the first parameter int into a radix representation as given in second parameter that can be octal, binay or hexa. Following program illustrates.

public class Demo
{
  public static void main(String args[])
  {
    Integer i1 = new Integer(100);
    int x = 10;
                                      // to convert i1 to String
    String integerString1 = i1.toString();               // 1st way
    System.out.println(integerString1);                  // prints 100
    String integerString2 = String.valueOf(i1);          // 2nd way
    System.out.println(integerString2);                  // prints 100

                                      // to convert x to String
    String intString1 = String.valueOf(x);               // 1st way
    System.out.println(intString1);                      // prints 10
    String intString2 = Integer.toString(x);             // 2nd way
    System.out.println(intString2);                      // prints 10
  }
}

valueOf() is a static method of String class that convert a primitive data type and an object into string form.

In the following program, the third toString(int, int) is used.

public class Demo
{
  public static void main(String args[])
  {
    String str1 = Integer.toString(100, 2);
    System.out.println("Binay representation of 100 is " + str1);

    String str2 = Integer.toString(100, 8);
    System.out.println("Octal representation of 100 is " + str2);

    String str3 = Integer.toString(100, 16);
    System.out.println("Hexadecimal representation of 100 is " + str3);
  }
}

image

The second parameter 2, 8, 16 of toString() indicates the first parameter 100 is to be converted to binary, octal and hexadecimal.

Another program is available that converts int to binary, otcal and hexa directly - int to Binary, Octal, Hexa Java.