Rd

151 views
93 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
151
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Rd

  1. 1. 6R8NJ3Importance of toString() in java>> Saturday, October 20, 2012TweetObject class of Java is having predefined toString() method. This method by default Object classcalls implicitly when an object created. Overriding toString manually is nothing butimplementing this method in our class.The java toString() method is used when we need a stringrepresentation of an object. It is defined in Object class.The toString() method is useful for debugging. By default, when an object is printed out in aprint stream like System.out, the toString() method of the object is automatically called.While develping the code the developers used to check the object properties are getting throughthe object or not. For this print statement will be useful to quick test in the console.public String toString()Returns: a string representation of the object.Let us take a Person class and try to print the person object using the System.out.println()statement.package blog.javabynataraj;//@author Muralidhar Nclass Person{public String fname;public String lname;Person(String fn,String ln){this.fname=fn;this.lname=ln;}public String getFname() {return fname;}public void setFname(String fname) {this.fname = fname;}public String getLname() {return lname;}public void setLname(String lname) {this.lname = lname;}}public class ToStringTest {public static void main(String[] args) {Person p = new Person("murali","dhar");System.out.println(p);}}
  2. 2. The output will be the class name@hexadecimalhere the Object classs method toString returninggetClass().getName()+@+Integer.toHexString(hashCode())But here we assumed that the firstname and the lastname will be print. But it is not done. This isthe magic toStirng method.But in the below program we can print the firstname and lastname of person Object. What we aregoing to do here is just overriding the toString method in Person Class.package blog.javabynataraj;//@author Muralidhar Nclass Person{public String fname;public String lname;Person(String fn,String ln){this.fname=fn;this.lname=ln;}public String getFname() {return fname;}public void setFname(String fname) {this.fname = fname;}public String getLname() {return lname;}public void setLname(String lname) {this.lname = lname;}public String toString(){return (getClass()+" FirstName: "+fname+" LastName: "+lname);}}public class ToStringTest {public static void main(String[] args) {Person p = new Person("murali","dhar");System.out.println(p);}}See the output of this:Now you can achieve this by overriding the default toString() method inside Person class toreturn the contents of the instance of Person.

×