Saturday 13 April 2019



                                                                toString( ) method :

We can use this method to get string representation of an object.

Whenever we are try to print any object reference internally toString() method will be executed.

If our class doesn't contain toString() method then Object class toString() method will be executed.

Example:
System.out.println(s1); => super(s1.toString());



class Student
{
String name;
int rollno;
Student(String name, int rollno)
{
this.name=name;
this.rollno=rollno;
}



public static void main(String args[]){
Student s1=new Student("Govind",101);
Student s2=new Student("Ajit",102);
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
}
}






In the above program Object class toString() method got executed which is implemented as follows.


In the above program Object class toString() method got executed which is implemented as follows.

public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
 
here  getClass().getName()  =>  classname@hexa_decimal_String_representation_of_hashCode


class Student1
{
String name;
int rollno;
Student1(String name, int rollno)
{
this.name=name;
this.rollno=rollno;
}

public  String  toString(){
return name+"........"+rollno;
}

public static void main(String args[]){
Student1 s1=new Student1("Govind",101);
Student1 s2=new Student1("Ajit",102);
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
}
}





To provide our own String representation we have to override toString() method in our class.
Ex : For example whenever we are try to print student reference to print his a name and roll no we have to override toString() method as follows.

public  String  toString(){
return name+"........"+rollno;
}



In String class, StringBuffer, StringBuilder, wrapper classes and in all collection classes toString() method is overridden for meaningful string representation. Hence in our classes also highly recommended to override toString() method.


class TestDemo{
public String toString(){
return "Test";
}
public static void main(String[] args){
Integer i=new Integer(10);
String s=new String("javatechnology");
TestDemo t=new TestDemo();
System.out.println(i);
System.out.println(s);
System.out.println(t);
  }
}





No comments:

Post a Comment