Changes to the Formal Parameter do not affect the Caller

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:

First  value of the local var: 7
Value of the parameter: 7
Second value of the local var: 7

Changes to the Formal Parameter
do not affect the Caller

Here is the program again, with a slight change. Now the invoked method print() makes a change to its copy of the value in its formal parameter x.

class SimpleClass
{
  public void print( int x )
  {
    System.out.println("First  value of the parameter: " + x );
    x = 100;       // local change to the formal parameter 
    System.out.println("Second value of the parameter: " + x );
  }
}

class SimpleTester
{
  public static void main ( String[] args )
  {
    int var = 7;
    SimpleClass simple = new SimpleClass();

    System.out.println("First  value of the local var: " + var );    
    simple.print( var );
    System.out.println("Second value of the local var: " + var );    
  }
}

Recall that this is using call by value which means parameters are used to pass values into a method, but not used to pass anything back to the caller.

QUESTION 4:

Now what is the output of the program?

First  value of the local var: 
First  value of the parameter: 
Second value of the parameter: 
Second value of the local var: