Junked Car

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 single reference variable car is used in turn for each object.

Junked Car

First car as Garbage

 

The output to the screen of this program is the same as the previous. However, since the reference variable car is used when the second Car is constructed, the first car becomes garbage before the end of the program.

Car car  = new Car( 32456, 32810, 10.6 );
System.out.println( "Miles per gallon of car 1 is " 
  + car.calculateMPG() );

car      = new Car( 100000, 100300, 10.6 );
System.out.println( "Miles per gallon of car 2 is " 
  + car.calculateMPG() );

The picture shows the situation just after the second car is constructed. The first car no longer has a reference to it, so it is now garbage.

QUESTION 15:

(Review Questions:)

  1. Do the instance variables of an object hold values for the lifetime of the object?
  2. Do the parameters of a constructor hold values for the lifetime of the object?