Changing a Reference 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

If print() changes the value held in st, will this change the actual object?

Answer:

No. Changing the reference will not change the object.

Changing a Reference Parameter

Here is an altered program in which the print() method changes the value held in its formal parameter.

class ObjectPrinter2
{
  public void print( String st )
  {
    System.out.println("First value of parameter: " + st );

    st = "Hah! A second Object!" ;

    System.out.println("Second value of parameter: " + st );

  }
}

class OPTester2
{
  public static void main ( String[] args )
  {
    String message = "Original Object" ;


    ObjectPrinter op = new ObjectPrinter();

    System.out.println("First  value of message: " + message );    

    op.print( message );

    System.out.println("Second value of message: " + message );    
  }
}

QUESTION 8:

What is the output of the program?

First  value of message: 
First value of parameter: 
Second value of parameter: 
Second value of message: