Automatic Call of toString()

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

What type of parameter does the System.out.println() method expect?

Answer:

It expects a reference to a String as a parameter.

Automatic Call of toString()

Actually, System.out.println() can deal with several types of parameters, and one of them is reference to a String. No version of System.out.println() was written to use a Point reference, however. So the following does not look like it will work:

Point a = new Point();  // a is a Point reference

System.out.println( a ); 
                    |
                    +--- should be String reference 

However, it does work, for the following reason:

When a parameter should be a String reference, but is a reference to another type of object, Java calls the object's toString() method to create a String and then uses the resulting String reference.

All objects (of any type at all) have their own toString() method, so this trick works with any object.

QUESTION 10:

(Puzzle: ) Does a String object have a toString() method?