Assigning to a Parameter

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

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

Answer:

Outside — so it can be "seen" and used by other methods.

Assigning to a Parameter

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. For example:

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 ; 
  }
}

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
  }
}

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.


QUESTION 8:

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

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

Is this OK?