go to previous page   go to home page   go to next page

Is the name of a method inside or outside the glass box?

Answer:

Outside — so it can be called by other methods.


Assigning to a Parameter

class CheckingAccount
{
  . . . .
  private int balance;

  public void processCheck( int  amount  )
  {                          
    int charge;
    if ( balance < 100000 )
      charge = 15; 
    else
      charge = 0;
    balance =  balance -  amount  - charge  ;

    // change the local copy of the value in "amount"
    amount = 0 ; 
  }
}

public class CheckingTester
{

  public static void main ( String[] args )
  {
    CheckingAccount act;
    int check = 5000;
    act = new CheckingAccount( "123-345-99", "Wanda Fish",  100000 );
           
    System.out.println( "check:" + check );     // prints "5000"

    // call processCheck with a copy of the value 5000
    act.processCheck( check );             

    System.out.println( "check:" + check );     // prints "5000" --- "check" was not changed
  }
}

A parameter is a "one-way message" that the caller uses to send values to a method.

Within the body of a method, a parameter is used just like any variable. It can be used in arithmetic expressions, in assignment statements, and so on.

However, changes made to the parameter do not have any effect outside the method body. A parameter is a local copy of whatever value the caller passed into the method. Any changes made to it affect only this local copy.

The formal parameter amount is the name used for the value 5000 that processCheck() has been sent. That method changes the value held in amount, but this has no effect on any other variable.

When the method returns to its caller, the value in the parameter amount and the value in the local variable charge are forgotten.


QUESTION 8:

Say that main() called the method with an integer literal:

act.processCheck( 7000 );  // call processCheck with the value 7000

Is this OK?


go to previous page   go to home page   go to next page