Skip to content
March 1, 2009 / Narayan

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.

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);
	}
}
Advertisements

4 Comments

Leave a Comment
  1. cotton.m / Jun 9 2009 2:17 am

    The toString() method is from java.lang.Object. Not java.lang.String.

  2. EJP / Jun 9 2009 4:03 am

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

  3. Narayan / Jun 9 2009 11:14 am

    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

  4. Narayan / Jul 10 2009 10:43 pm

    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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: