Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / First Aid / December 2007

Tip: Looking for answers? Try searching our database.

question about the toString Method

Thread view: 
Art Cummings - 27 Dec 2007 17:46 GMT
Hello everyone,

I've been trying to understand how the toString Method works.  I've been
looking at this during the semester break so the instructor hasn't been
available for questions.  Specifically i'm trying to understand why the
System.out.println method calls the toString method in my Course class.
I've included the bare minimum, that I think is necessary to understand the
question i'm asking.  I omitted the Textbook and Instructor classes.  What's
confusing me is why there seems to be nothing in the calling statement to
direct the flow of the program to the toString method in the Course class.

thanks to anyone that can shed some light

Art

*******************MAIN CLASS****************************************

/**
  This program demonstrates the Course class.
*/

public class CourseDemo
{
  public static void main(String[] args)
  {
     // Create an Instructor object.
     Instructor myInstructor =
         new Instructor("Kramer", "Shawn", "RH3010");

     // Create a TextBook object.
     TextBook myTextBook =
         new TextBook("Starting Out with Java",
                      "Gaddis", "Scott/Jones");

     // Create a Course object.
     Course myCourse =
        new Course("Intro to Java", myInstructor,
                   myTextBook);

     // Display the course information.
     System.out.println(myCourse);    **************WHY DOES THIS CALL THE
toString method in the Class course?****************
  }
}

*************COURSE CLASS*******************
/**
  This class stores data about a course.
*/

public class Course
{
  private String courseName;      // Name of the course
  private Instructor instructor;  // The instructor
  private TextBook textBook;      // The textbook

  /**
     This constructor initializes the courseName,
     instructor, and text fields.
     @param name The name of the course.
     @param instructor An Instructor object.
     @param text A TextBook object.
  */

  public Course(String name, Instructor instr,
                TextBook text)
  {
     // Assign the courseName.
     courseName = name;

     // Create a new Instructor object, passing
     // instr as an argument to the copy constructor.
     instructor = new Instructor(instr);

     // Create a new TextBook object, passing
     // text as an argument to the copy constructor.
     textBook = new TextBook(text);
  }

  /**
     toString method
     @return A string containing the course information.
  */

  public String toString()      *********************** WHY IS THIS CALLED
BY System.out.println?****************************
  {
     // Create a string representing the object.
     String str = "Course name: " + courseName +
                  "\nInstructor Information:\n" +
                  instructor +
                  "\nTextbook Information:\n" +
                  textBook;

     // Return the string.
     return str;
  }
}
david.w.burhans@gmail.com - 27 Dec 2007 19:03 GMT
Anytime something in Java receives an object and wants a String, it
calls the objects toString() method.

toString() is defined for the Object class; the base class of all
classes in Java.

> Hello everyone,
>
[quoted text clipped - 10 lines]
>
> Art
Patricia Shanahan - 27 Dec 2007 20:21 GMT
> Anytime something in Java receives an object and wants a String, it
> calls the objects toString() method.

This might give the impression that toString is called in many more
situations than is actually the case. For example, I often receive an
Exception and want a String. In many cases, the String I want is the
getMessage() result, not the toString() result.

The call to toString in the original program is the result of specific
documented behavior of PrintStreams println method, applied to a
non-null Object reference.

Patricia
Patricia Shanahan - 27 Dec 2007 19:42 GMT
> Hello everyone,
>
[quoted text clipped - 6 lines]
> confusing me is why there seems to be nothing in the calling statement to
> direct the flow of the program to the toString method in the Course class.
...
>       // Create a Course object.
>       Course myCourse =
[quoted text clipped - 6 lines]
>    }
> }
...
>    public String toString()      *********************** WHY IS THIS CALLED
> BY System.out.println?****************************

This is really a question about PrintStream's println method with an
Object argument. See its API documentation at e.g.
http://java.sun.com/j2se/1.5.0/docs/api/java/io/PrintStream.html#println(java.la
ng.Object
)
It refers to the corresponding print method's documentation.

The print method's documentation says "Print an object. The string
produced by the String.valueOf(Object) method is translated into bytes
according to the platform's default character encoding, and these bytes
are written in exactly the manner of the write(int) method."

That links to the String.valueOf(Object) documentation which says
'Returns: if the argument is null, then a string equal to "null";
otherwise, the value of obj.toString() is returned.'

Therefor System.out.println(myCourse) calls myCourse.toString().

Patricia
Eric Sosman - 27 Dec 2007 19:46 GMT
> Hello everyone,
>
[quoted text clipped - 9 lines]
>       System.out.println(myCourse);    **************WHY DOES THIS CALL THE
> toString method in the Class course?****************

    First, println() is not one method but a whole family of
methods of the PrintStream class.  There's a println() method
that takes an int argument, another that takes a double, yet
another that takes no argument at all.  The particular one
you're calling is the println() that takes an Object.

    So, what does the println(Object) method of PrintStreamClass
do?  First thing, right off the bat, is it calls the static
String.valueOf() method on the same object, and from that it
gets a String which it then prints.  Like println() itself,
String.valueOf() has many versions for many argument types, and
the one we wind up with is String.valueOf(Object).

    Over to the String class; what does String.valueOf(Object)
do?  It depends: If the argument is null it just returns the
four-character String "null".  Otherwise -- ta-daaah! -- it
calls the object's own toString() method to get a String, and
that's where the call to Course's toString() method comes from:

    You call
      System.out.println(myCourse), which calls
         String.valueOf(myCourse), which calls
            myCourse.toString(), which returns a String to
         String.valueOf(myCourse), which returns the same String to
      System.out.println(myCourse), which then calls
         System.out.print(theString), which returns to
      System.out.println(myCourse), which eventually returns to
    You.

Signature

Eric Sosman
esosman@ieee-dot-org.invalid

Art Cummings - 28 Dec 2007 15:59 GMT
> You call
>    System.out.println(myCourse), which calls
[quoted text clipped - 5 lines]
>    System.out.println(myCourse), which eventually returns to
> You.

Thanks Eric,

I think I follow what you're saying.  My Java intermediate course is
starting in a couple of weeks.  I'm wondering at what point concepts like
this are introduced.  Is this a graduate level understanding?  The text by
Tony Gaddis, Starting out with Java, is pretty good, but it drives me crazy
when he leaves out explanations of this type.  I'm wondering whether it's
better just to accept what's happening, at my level, or to dig deeper.  I
definitely feel that sometimes the ideas have to sit for awhile before they
just seem to gell.

Thanks again

This was pretty clear.

Art
Patricia Shanahan - 28 Dec 2007 16:16 GMT
>> You call
>>    System.out.println(myCourse), which calls
[quoted text clipped - 16 lines]
> definitely feel that sometimes the ideas have to sit for awhile before they
> just seem to gell.

All the data in the quote from Eric is stated in the API documentation
at e.g. http://java.sun.com/j2se/1.5.0/docs/api/index.html. It could be
found from first principles:

1. Note that System is an API class and you don't have to import it, so
select the java.lang package and look for System in its classes.

2. From the System documentation find that System.out is of type
PrintStream and follow the link to the java.io.PrintStream documentation.

3. Look in the PrintStream documentation for println with a general
Object argument.

Carry on like this, until you have found enough data for your current
purposes. It may be worth your while to work through the question,
comparing what you see in the documentation to what Eric wrote.

Fluent use of the API documentation is one of the most important Java
skills. People without that skill are dependent on whatever summaries
appear in books and tutorials they use. People with API documentation
reading skill can use the full range of Java features. Even non-Sun
add-in packages for Java usually have documentation in the same format.

Patricia
Art Cummings - 29 Dec 2007 03:29 GMT
> Fluent use of the API documentation is one of the most important Java
> skills. People without that skill are dependent on whatever summaries
[quoted text clipped - 3 lines]
>
> Patricia

Thanks Patricia, I do find it difficult to understand what's being said
there, now I understand that it's an acquired skill.  I'm going to start
spending time trying to become familiar with it.

Thanks
Art
Patricia Shanahan - 29 Dec 2007 14:31 GMT
>> Fluent use of the API documentation is one of the most important Java
>> skills. People without that skill are dependent on whatever summaries
[quoted text clipped - 7 lines]
> there, now I understand that it's an acquired skill.  I'm going to start
> spending time trying to become familiar with it.

The best way I know is to pick some question, such as your question
about what happens when you call System.out.println(myCourse), and try
to track down the information through the documentation.

Patricia
Stefan Ram - 28 Dec 2007 16:37 GMT
>starting in a couple of weeks.  I'm wondering at what point concepts like
>this are introduced.  Is this a graduate level understanding?  The text by

 This depends on the teacher or book.

 Whenever you learn on about a language, you will learn
 things you did not learn in the first class about it.

 You might ask: »Why has he not told us this?«

 The answer is that not everything can be put into a
 single first class (enduring some months or so).
 So the teacher or academic often is not to blame for omissions.

 Some important aspects can not be taught until more
 basic concepts are known.

 It depends on you. You've got to keep on learning after
 the first class to become good at anything. See also

http://norvig.com/21-days.html
Art Cummings - 29 Dec 2007 03:35 GMT
>  It depends on you. You've got to keep on learning after
>  the first class to become good at anything. See also
>
> http://norvig.com/21-days.html

Thanks Stefan, this puts it in perspective.

Art
Eric Sosman - 28 Dec 2007 18:36 GMT
>> You call
>>    System.out.println(myCourse), which calls
[quoted text clipped - 11 lines]
> starting in a couple of weeks.  I'm wondering at what point concepts like
> this are introduced.  Is this a graduate level understanding?  [...]

    No, I wouldn't say so.  The approach Patricia Shanahan
suggests ("RTFM") is usually best: The Javadoc is supposed to
tell you what the method does, and (if appropriate) how it
does it.  In this case, the Javadoc for the System class tells
you that the `out' member is a PrintStream, the Javadoc for
the println(Object) method of PrintStream tells you that it
calls String.valueOf() on the object, and the Javadoc for the
valueOf(Object) method of String tells you that it uses the
toString() method of the object's class.

    Sometimes the Javadoc omits something you need to know
(or tells you something it really shouldn't).  In this case
you can consult the source; I use NetBeans, which can take me
straight to the source code of a standard Java method I'm
curious about.  But there's some peril in this approach, because
when you look at the source for PrintStream, say, it can be hard
to tell which parts are guaranteed and will be part of PrintStream
for ever and ever, and which parts are happenstance and might be
different in the Java 9 release.  Still, when the Javadoc doesn't
quite fulfill its purpose -- or when you're just curious -- a
peek at the source has value.

Signature

Eric Sosman
esosman@ieee-dot-org.invalid

Mark Space - 28 Dec 2007 19:55 GMT
> I think I follow what you're saying.  My Java intermediate course is
> starting in a couple of weeks.  I'm wondering at what point concepts like
> this are introduced.  Is this a graduate level understanding?  The text by

I'm curious what level you are now.  You sound like someone who has just
finished their first freshman semester.

I'd say you should understand how to read a spec (especially one like
the JLS, which is pretty darn easy to read) by the beginning of your
senior (undergraduate) year, at the latest, and by the end of your
second year it should be much easier and more natural.  However, don't
wait for your instructors to spoon feed it to you.  Start on your own.
(Starting right now with just having done your first class may be a bit
impractical.)

I think technology moves much faster now than it did 20 years ago.  A
course designed specifically to teach a programmer how to stay up with
current trends would be a great idea.

Companies love to send educational stuff to schools.  Work out a deal
with your instructors or local chapter of the ACM for "extra studies"
courses working with companies to understand their products and specs.
Even if you couldn't take the course yet, it'll be good to get the ball
rolling and have someone else be the first guinea pig.  New courses tend
to be a mess.

Don't be afraid to read company specs, IEEE documents, ANSI, RFC, ISO,
etc.  Work out a course on "who are these guys and how do I get their
stuff" even if it's just 0.5 units or less.  How does a programmer
obtain and understand a specification?  That should be the goal of the
course.  There are also meeting minutes and other services that explain
the specs further.  These often costs money; your school might pay for a
subscription as part of a course.  Always spend other people's money if
possible.
Art Cummings - 29 Dec 2007 03:40 GMT
>> I think I follow what you're saying.  My Java intermediate course is
>> starting in a couple of weeks.  I'm wondering at what point concepts like
[quoted text clipped - 3 lines]
> I'm curious what level you are now.  You sound like someone who has just
> finished their first freshman semester.

You pegged it, i'm a freshman or was, this was my first Java and C++ course.
I've taken visual basic but it didn't involve classes.  I'm going to ask my
instructors if there is any program like what you're mentioning.  I
forwarded him your post.

Thanks
Art
Mark Space - 29 Dec 2007 19:27 GMT
> You pegged it, i'm a freshman or was, this was my first Java and C++ course.
> I've taken visual basic but it didn't involve classes.  I'm going to ask my
> instructors if there is any program like what you're mentioning.  I
> forwarded him your post.

Just curious, what school are you at?
Art Cummings - 30 Dec 2007 20:15 GMT
> Just curious, what school are you at?

Dekalb tech in Georgia
Mark Space - 27 Dec 2007 19:52 GMT
> I've included the bare minimum, that I think is necessary to understand the
> question i'm asking.  I omitted the Textbook and Instructor classes.  What's
> confusing me is why there seems to be nothing in the calling statement to
> direct the flow of the program to the toString method in the Course class.

You pass a reference to an object, it calls toString() on that reference.

public static void myPrintln( Object obj ) {
  String s = obj.toString();
  System.out.println( s );  // would actually use a different
                            // call here...
}

Get it?

The confusing one is how does the compiler know to call toString() when
concatenating strings:

  String s = "This is a: " + obj;

Answer: the compiler is specially crowbarred to call toString() in that
instance.
Art Cummings - 27 Dec 2007 21:26 GMT
> You pass a reference to an object, it calls toString() on that reference.
>
[quoted text clipped - 13 lines]
> Answer: the compiler is specially crowbarred to call toString() in that
> instance.

Thank you everyone, it's a little clearer now.

Art
Lew - 28 Dec 2007 00:20 GMT
>> You pass a reference to an object, it calls toString() on that reference.
>>
[quoted text clipped - 15 lines]
>
> Thank you everyone, it's a little clearer now.

Ain't the Javadocs a wonderful thing?

Signature

Lew

Stefan Ram - 27 Dec 2007 23:06 GMT
>I've been trying to understand how the toString Method works.

 There are several toString() methods in different classes.

>Specifically i'm trying to understand why the
>System.out.println method calls the toString method in my
>Course class.

 Because someone decided that this would be useful and wrote a
 corresponding API specification and method declaration.

 Actually it does not call the »toString()« method of your
 class, but of /any/ argument object.

 The expression used in println probably looks liks

Primary.toString()

 , where »Primary« is a primary expression.

 This will be resolved (bound) to the »toString()« method of
 the object referenced by »Primary« when it is being evaluated.
 This is called »object-oriented programming« or »late-binding«
 or »polymorphism«.

>I've included the bare minimum, that I think is necessary to
>understand the question i'm asking.

 Your question was already completely given and did not refer
 to any custom code. So, there is no more code necessary.
Roedy Green - 27 Dec 2007 23:40 GMT
On Thu, 27 Dec 2007 12:46:52 -0500, "Art Cummings"
<aikiart7@gmail.com> wrote, quoted or indirectly quoted someone who
said :

> System.out.println(myCourse);    **************WHY DOES THIS CALL THE
>toString method in the Class course?****************

Have a look at how println is implemented. Look in src.zip.

In essence it looks something like this

 void println ( Object o )
 {
 // the console needs a string of chars.  I just have an object
 // so I will call the the toString method which every object has
 // or overrides.
 sendToConsole ( o.toString() );
 println();
 }

Why?  How else would you get a String to print?
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Chase Preuninger - 31 Dec 2007 01:03 GMT
Well if it doesnt call the toString method, what the hell is
System.out going to know what to print.  It calls the toString because
it is always there, since it is inherited from object.  Since you
overrode that method in your class System.out calls it to get the
string representation.  If you want to see what the toString method
would display if you dident override it, simply don't override it, or
return super.toString().  And if you want both implementations, make a
separate getter method for either on of them.
Chase Preuninger - 31 Dec 2007 01:04 GMT
Asking a question like that I would also assume you are new to Java.
Eric Sosman - 31 Dec 2007 14:25 GMT
> Asking a question like that I would also assume you are new to Java.

    Making a post like that I would also assume you are new
to Usenet.  (In other words, quote enough context in your
reply so that the reply can stand alone as a complete message.)

Signature

Eric Sosman
esosman@ieee-dot-org.invalid



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.