First value of the result: 0 Second value of the result: 14
Object references can be parameters. Call by value is used, but now the value is an object reference. Since the invoked method has a reference to an object, it can access that object and possibly change it. Here is an example program:
class ObjectPrinter { public void print( String st ) { System.out.println("Value of parameter: " + st ); } } class OPTester { public static void main ( String[] args ) { String message = "Only One Object" ; ObjectPrinter op = new ObjectPrinter(); System.out.println("First value of message: " + message ); op.print( message ); System.out.println("Second value of message: " + message ); } }
In this program, the local variable message
contains a reference to a String
object.
A copy of that reference is made in the formal parameter st
of the print()
method.
The object is not copied.
What is the output of the program?
First value of message: Value of parameter: Second value of message: