Program that uses the toString() Method

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

Answer:

A parameter is an item of data supplied to a method or a constructor.

Program that uses the toString() Method

The documentation shows that toString() needs no parameters. However, you must use parentheses when the method is called. Here is the example program:

import java.awt.*;
class PointEg2
{

  public static void main ( String arg[] )
  {
    Point a, b, c;              // reference variables

    a = new Point();            // create a Point at ( 0,  0); 
                                // save the reference in "a"
    b = new Point( 12, 45 );    // create a Point at (12, 45); 
                                // save the reference in "b"
    c = new Point( b );         // create a Point

    String strA = a.toString(); // create a String object based on the data
                                // found in the object referenced by "a".
    System.out.println( strA );
  }
}

When this program runs, the statement:

String strA = a.toString(); // create a String object based on the data 

creates a String object based on the data in the object referred to by a. The strA refers to this new String object. Then the characters from the String are sent to the monitor with println. The program prints out:

java.awt.Point[x=0,y=0]

The Point object has not been altered: it still exists and is referred to by a. Sometimes people say that toString() converts the Point object to a String, but this is sloppy. Nothing has been converted, but a new object has been created.

QUESTION 8:

Just as the program is about to end, how many objects have been created? Has any garbage been created?