Possible Errors

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:

  1. Do the instance variables of an object hold values for the lifetime of the object?
    • Yes—an object is a "thing" that has state (its unique characteristics.) The state is kept in instance variables.
  2. Do the parameters of a constructor hold values for the lifetime of the object?
    • No—the parameters of a constructor are part of a temporary "message" to the constructor. After the parameters have been used, they are gone.

Possible Errors

Of course, the data in the "message" to the constructor will usually be stored in the instance variables, where it will remain until the object is destroyed (or until the instance variables are deliberately changed).

Here is an interesting program. Is anything wrong?

class Car
{
  // instance variables
  double startMiles;   // Stating odometer reading
  double endMiles;     // Ending odometer reading
  double gallons;      // Gallons of gas used between the readings

  // constructor
  Car( double first, double last, double gals )
  {
    startMiles = first ;
    endMiles   = last ;
    gallons    = gals ;
  }

  // methods
  double calculateMPG()
  {
    return  (last - first)/gals  ;
  }

}

class MilesPerGallon
{
  public static void main( String[] args ) 
  {
    Car car = new Car( 32456, 32810, 10.6 );
    System.out.println( "Miles per gallon is " + car.calculateMPG() );
  }
}

QUESTION 16:

Examine the program. Is there anything wrong?