A good question came with a nitpick submission that I got so I'm posting it here so more people can see it (and undoubtedly improve my answer . The question: If you get the day, date and time by using the object only what is toString for? (Here "the object" refers to a Date object). [ August 28, 2003: Message edited by: Pauline McNamara ]
I'm not sure I understand the full context, but what I think they are referring to is how toString automagically gets called whenever an object, ANY object, is placed within a print or println statement. So System.out.println( new Date() ); is the same thing as System.out.println( new Date().toString() ); Is this what is being asked?
There are a couple of possible answers to that... 1) In places where you are using the object that will convert a String, such as in a println, toString() is redundant except for documentation purposes. 2) In places where you are using the object that need a String, such as a parameter to a method call, toString() is usually needed to provide the String value instead of an object reference.
Joined: Jan 19, 2001
Here's how I was going to answer it...
I'll start by bouncing back a different question to you: what does the print method do for you? (I'll get back to that in a sec.) toString gives you, like its name suggests, a String representation of the object you call it on. In this case it gives you the current day, date and time. Almost all objects have a toString method that do this for you. Here's the cool thing though. When you pass an object only (without toString) to the print or println method, you automatically get the same thing as you would if you'd called toString explicitly. (There's more going on back there, like a little detour to another method called String.valueOf(Object), but we don't really need to worry about that.) Let's say you weren't trying to print the Date object, but wanted to do something else with it where you needed it to be a String. Maybe you want to store it in a variable as a String - that's when a Date object's toString method might come in handy.
What means "using the object only"? If you pull something like System.out.println( new SomeObject() ); or SomeObject someObject = new SomeObject(); System.out.println( someObject ); toString() is called behind the scenes. Look at the docs for PrintStream.println(Object), PrintStream.print(Object), and String.valueOf(Object) for further details.
Joined: Mar 25, 2001
And don't forget how nulls get handled with kid gloves in all of this. See this old thread for details.
Joined: Jan 19, 2001
Hey! Wait til I finish typing for cryin' out loud! You guys just hanging out on the prowl around here? Sheesh. [ August 28, 2003: Message edited by: Pauline McNamara ]