Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using toString().......

 
Steve Jensen
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9066
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic