ToString() method

The toString() method is one of the feature of java. It is the method of class String which is imported default on JVM from java.lang.Object;

ToString() method is one of the display method.

When ever we tries to print the text from System.out.println("Hello"); then it directly inherit from the toString() method. We can override the toString() method and make the println to print what we desire.

For eg.

[sourcecode=’java’]public class Student{
private String name;
private String ssn;
public Student(String dName, String dSsn){
//set value to accessor method of private attributes
this.setName(dName);
this.setSsn(dSsn);
}
//accessor method…..
public String toString(){
return “Student Name : ” +this.getName()+”nSsn : ”
+ this.getSsn();
}

//main method
public static void main(String[] args){
//let create a object
Student s1 = new Student(“Narayan”, “12345”);
/*this is the line where we can print without
defining any method but on jvm it is really
inheriting with toString() method to display
*/

System.out.println(s1);
}
}[/sourcecode]

4 thoughts on “ToString() method”

  1. oh ! dat’s my mistake i ‘ll repair it.

    I know dat it’s a method which has been defined in Object Class

    from java.lang.Object

  2. Type your comment here

    EJP :

    This is all rubbish. The toString() method is inherited from java.lang.Object.

    chech out this again

Leave a Reply