• Post Reply Bookmark Topic Watch Topic
  • New Topic

How toString method appears to be used without being explicitly called?  RSS feed

 
Mark Richardson
Ranch Hand
Posts: 108
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have two classes: Olive.java and Main.java

The Olive class is as follows:



and the Main class is like so:

package core.generics;

import java.util.ArrayList;

public class Main {




When I run this code, the println() prints out human-readable contents of the array instance "olives2."
This would make sense to me if I had said something like: "println(toString(olives2));
but from my limited understanding the toString method appears to have been magically applied to olives2. What sorcery is this?? :O
 
Mark Richardson
Ranch Hand
Posts: 108
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry I  did not enclose my code properly. My "Main" class is as follows:

 
Norm Radder
Rancher
Posts: 2240
28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
  the toString method appears to have been magically applied to olives2

yes.  The compiler adds a call to the toString method as needed. Another compiler undercover operation is  boxing and unboxing primitives to objects and back.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Norm Radder wrote:The compiler adds a call to the toString method as needed.

In this case it's not really compiler magic. The println(...) method calls toString() on the object that you pass to it.

You can look at the source code of PrintStream.println(Object x). It looks like this:

The first thing it does is call String.valueOf(x). The source code of that method looks like this:

And there you see how it is calling toString() on the object that was passed to it.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Mark Richardson wrote:. . . "println(toString(olives2)); . . .
You mean System.out.println(olive2.toString()); surely.

That code does call toString() somewhere. Look in the documentation for the System class and look for out, which you will find under Fields. You will see that out is a PrintStream, so click on PrintStream (or one of the See also links). Click on the METHOD link and find println(Object) and you will see it behaves like print(Object) plus something else. So click on print(Object) and you will see it calls String#valueOf. So find String#valueOf and see whether that says anything about toString.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!