More about Objects and Classes

The relational operations on primitive data are ==, >=, <=, >, <, and !=. They compare two data values, when those values' type has an ordering. For example, integers are ordered by size or magnitude. The result of a relational operation is a boolean value: either True or False. The relational operators on objects like Strings are different, and they are expressed as methods. Pay special attention to the equality method, equals().

9. Using a Temporary Object


Just as the program is about to close, how many objects have been created?     Four, counting the String object.

Has any garbage been created?    No, because a reference variable points to each object.

Using a Temporary Object

Here is another modification to the example program:

import java.awt.*;
class PointEg3

  public static void main ( String arg[] )
    Point a = new Point();              // declarations and construction combined 
    Point b = new Point( 12, 45 );    
    Point c = new Point( b );

    System.out.println( a.toString() ); // create a temporary String based on "a"

This program creates three Points with the same values as before, but now the declaration and construction of each point is combined.

The last statement has the same effect as the last two statements of the previous program:

  1. When the statement executes, a refers to an object with data (0,0).
  2. The toString() method of that object is called.
  3. The toString() method creates a String object and returns a reference to it.
  4. At this point of the execution, you can think of the statement like this:
    System.out.println( reference to a String );
  5. The println method of System.out uses the reference to find the data to print out on the monitor.
  6. The statement finishes execution; the reference to the String has not been saved anywhere.

Since no reference was saved in a reference variable, there is no way to find the String object after the println finishes. The String object is now garbage. That is OK. It was only needed for one purpose, and that purpose is completed. Using objects in this manner is very common.

Question 9:

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