What is the purpose of toString()?

Discussion in 'Java Language Basics/Fundamentals' started by naveenm_006, Aug 13, 2009.

  1. naveenm_006

    naveenm_006 New Member

    What is the purpose of toString()? and where it is used if possible tell me with one example.


  2. adityasharma00

    adityasharma00 New Member

    - toString() is a method of Object class.
    - Any class can use toString() mehod for describe self.

    Example :
    /** ToStringExample.java */
       class calculateTax{ 
           int calculateTax (float income){
           String toString() {
              S.o.p("Using this class we can calculate the tax. [More Information]");
        public class ToStringExample {
           public static void main(String[] args) {
             S.o.p(new calculateTax());
              // If class use toString() method then S.o.p will display the written information in this method
              // If class does not use toString() method then S.o.p will display [classname@hashCodeNo].
  3. soumya866

    soumya866 New Member

    To provide our own meaningful string representation we should override toString() method in our class.
    Whenever we are passing object reference to System.out.println internally jvm calls toString() method on that object reference. The resulting string will be displayed to console.
    If we are not overriding toString() then the object class toString() will be called.
    class Student
    String name;
    int roll no;
    Student(String name, int rollno)
    public String toString()
    return name+"------"+rollno;
    public static void main(String[] args)
    Student s1=new Student("aaa",111);
    Student s2=new Student("bbb",151);
    when u compile and run abve program the output is
    if we are not overriding toString() u willl get some
    Student@2bbb86..{Hash code}
    Student@1a33f11{Hash code}
  4. khadangap

    khadangap New Member

    Hi Friends,

    From my experience when we write System.out.println("some string "+ referencevariable);

    If the referenceVariable is String / primitive / wrapper type then it will call the toString() method of Object class. Which will return a String inatialised by "referenceVariable" . But when the reference variable is referencing to an user defiend class type such as public class Myclass{------ } then to print the object at first we have to override the toString() method of object class which will return the exact defination of the object otherwise you cant under stand the return string which is the combination of "classname + @ + something " which is not the exact defn of object

    Example :
    public class Myclass {
    int a;
    int b;
    public Myclass(int a, int b){
    /*public String toString(){                       //line no 7 ,8, 9
    return " a= " +a + "and  b =" +b; 
    } */
    public static void main(String arg[]){
    Myclass myclass = new Myclass(10,20);
    System.out.println("my object is : "+myclass);
    //here this will call the over ridden toString method of Myclass and will print the written value of the called method.
    Note :

    1. The above program will give the out put : My object is : Myclass@10b6269 which is not the required object defination.

    2. By un commenting line no 7,8,9 ( THAT MEANS BY OVERRIDING TOsTRING)u will get the following OUT PUT
    myclass object is : a = 10 and b = 20
    Buttom line:

    When you want to the real meaning of an object of an user defined type you have to over ride toString() method of Object class which ll written a strint as u described . other wise it will call the ToString() method of Object class which will return a not understanding string which is useless for us.

    Hello friend I m very poor in english . So try 2 understan by running the code.
  5. pawan_mangal

    pawan_mangal New Member

    Hi Friends

    String, Wrapper class already overridden the toString() method of Object class so why it Return meaningful representation of String and Wrapper Object.
  6. khadangap

    khadangap New Member

    hi friend,

    Ur arguement is right but i have mentioned that in case of user defined classes only we cannot get the exact defination of an object. Since String & wrapper classes are pre defind in API and though they overrides toString() we have no headach. According to the toString() of String And Wrapper classes they prints the string.

    I think it will help u.
  7. pawan_mangal

    pawan_mangal New Member

    ya definatelly but so many classes in java api do not have implementation of toString() of Object class like -what about BufferedReader (any I/O Related class) and also HashMap (may be).

    Am I right ?
  8. khadangap

    khadangap New Member

    Hi friend ,

    Thanks to give me suggetion but I m confused what u going to tell me ? Please clarify it .
  9. kirankumarm

    kirankumarm New Member

    Object : Object is a super class for all the classes.

    The methods in Object class as follows :

    Object clone( )
    final void notify( )
    Int hashCode( )
    Boolean equals( )
    final void notify( )
    Void finalize( )
    String toString( )
    Final Class getClass( )
    final void wait( )

    toString() : An instance method that converts the object to a string.
  10. pawan_mangal

    pawan_mangal New Member

    Friends sorry for confused you my point is that every class in java don't override toString() method eg- BufferedReader.

Share This Page