File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Using toString()....... Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Using toString()......." Watch "Using toString()......." New topic
Author

Using toString().......

Steve Jensen
Ranch Hand

Joined: Sep 23, 2002
Posts: 126
Folks, the short piece of code illustrates the use of toString().


But there is one thing I don't follow:-
How does the method public String toString() in class Box get called, if we have not explicitly stated it should???

Any help would be greatly appreciated.

Cheers in advance.


John Bonham was stronger, but Keith Moon was faster.
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Hi,
I think the toString() on Box got called on this line
String s = "Box b: " + b;
as String concatenation trigger the call to toString() of Box.
Originally posted by Steve Jensen:
Folks, the short piece of code illustrates the use of toString().


But there is one thing I don't follow:-
How does the method public String toString() in class Box get called, if we have not explicitly stated it should???

Any help would be greatly appreciated.

Cheers in advance.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
The toString() on Box got called on this line

String s = "Box b: " + b;

as String concatenation triggers the call to toString() of Box.


Yes, it's one of the automagic shortcuts that the people who designed Java created. If you concatenate a String with something else, the toString() method of the something else is automatically called. It works with primitives (even though primitives don't really have a toString method per se) as well as with objects.


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
John Smith
Ranch Hand

Joined: Oct 08, 2001
Posts: 2937
How does the method public String toString() in class Box get called, if we have not explicitly stated it should
If you call System.out.println(box), the "toString()" method will also be called. This happens to be a nice mechanism for debugging purposes, as you can print the state of the object at run time when diagnosing the problem. So overriding the "toString" method of your classes is always a good idea.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Using toString().......