• Post Reply Bookmark Topic Watch Topic
  • New Topic

What's the difference??  RSS feed

 
Andrew Hartman
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, sorry this might sound like a stupid question, but can someone one explain to me the difference between System.out.println() and the toString method? What difference cases are they used in, and why?
Thanks
 
John Croucher
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey there are no stupid questions. The System.out.println("text text text") is used to display whatever text is between the quotes. (Or the string representation of any primitive values between the ().
On the other hand toString() returns a string that "textually represents" an object. However, the toSring method in and of itself will not display the text to the user. To do that you would need to combine both the System.out.println() and toString.
Example:
System.out.println("Here is an object: " + myObject.toString());
This would display the text "Here is an object " followed by the values for the object myObject.
The best way to get a grasp on the use of these is to write a small program and try both of them out.
View this link to see more on toString(): http://java.sun.com/j2se/1.3/docs/api/java/lang/Object.html
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method toString() is a method inherited from Object class. We need to override it so that our own objects would return meaningful descriptions about it, usually its state.
But toString() simply returns a String object, a simple way to display it is to use System.out.println().
Suppose we have an object myObject, you must be wondering why System.out.println(myObject); and System.out.println(myObject.toString());
might return the same value. Because the toString() was used in the 1st println too!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!