MORE PARAMETER PASSING EXAMPLES

NOTE: This set of www pages is not the set of www pages for the curent version of COMP101. The pages are from a previous version that, at the request of students, I have kept on line.


CONTENTS

1. Passing strings to and from methods
 
2. Passing object references



1. PASSING STRINGS TO AND FROM METHODS

In an earlier example we presented the call by reference concept by passing references to arrays. We can do the same thing with references to instance of the class String (remember, a string is essentially a charcater array). A simple exmaple is presented in Table 1 where the user is invited to input a string which is then passed to a method (method1) using the call be reference mechanism. Here we do something to the string (convert to upper case using the toUpperCase method defined in the string class that comes with the Java API), and then return the result.

 

Some sample output produced by the code presented in Table 1:

$ java StringPassing
Input a string frans
Input string = frans
New string   = FRANS 
// RETURNING A STRING FROM A METHOD
// Frans Coenen
// Tuesday 29 August 2000
// The University of Liverpool, UK

import java.io.*;

class StringPassing {

    // ------------------- FIELDS ------------------------ 
                          
    // Create BufferedReader class instance

    public static InputStreamReader input      = new InputStreamReader(System.in);
    public static BufferedReader keyboardInput = new BufferedReader(input);
                          
    // ------------------ METHODdS -----------------------
                          
    /* Main method  */

    public static void main(String[] args) throws IOException {
                              
        // Read input
                              
        System.out.print("Input a string ");
        String inputString = keyboardInput.readLine();
	
	// Method call
	
	String newString = method1(inputString);
	
	// Output
	
	System.out.println("Input string = " + inputString);
	System.out.println("New string   = " + newString);
        }     
    
    /* Method 1 */
    
    public static String method1(String inString) {
        
	// Do something to input string (convert to upper case) 
	
	String outString = inString.toUpperCase();
	
	// Return string
	
	return(outString);
	}
    }

Table 1: String passing




PASSING OBJECT REFERENCES

In the above example we used the call by reference mechanism to pass an instance of the class String. We can in fact use the mechanism to pass references to any isntance (i.e. to pass entire objects). In Table 2 a trivial class definition is presented; in Table 3 some application code is presented which utilises the Data class presented in Table 2. Remeber that when we do this we a working with the actual object and bot a copy of it, thus anything we do to the object within the called metrhod(s) will be effective veyonf the life time of the method call.

Runnning the application presented in Table 3 will produce:

$ java CallByRefApp
METHOD 1: Before call by reference
dataInst1: number1 = 1, number2 = 2.
METHOD 1: After call by reference
dataInst1: number1 = 2, number2 = 4.

METHOD 1 (copy opf original instance): 
Before call by reference
dataInst1: number1 = 2, number2 = 4.
dataInst2: number1 = 2, number2 = 4.
METHOD 1: After call by reference
dataInst1: number1 = 3, number2 = 6.
dataInst2: number1 = 3, number2 = 6.

METHOD 2: Before call by reference
dataInst1: number1 = 3, number2 = 6.
dataInst2: number1 = 3, number2 = 6.
dataInst3: number1 = 0, number2 = 0.
        dataInstX: number1 = 3, number2 = 6.
        dataInstY: number1 = 3, number2 = 6.
        dataInstX: number1 = 4, number2 = 8.
        dataInstY: number1 = 4, number2 = 8.

METHOD 2: After call by reference
dataInst1: number1 = 4, number2 = 8.
dataInst2: number1 = 4, number2 = 8.
dataInst3: number1 = 0, number2 = 0.
 

Notes:

  • In the first call to method1 we changed the values of dataInst1 which has the effect of changing the actual values (we do not work with a copy of dataInst1 inside method1 as is the case with "call by value").
  • We then assign the reference value associated with dataInst1 to dataInst2 and call method1 again but with this second reference. However both references refer to the same object and thus any changes made using dataInst2 have the same effect as making changes to dataInst1 (as demonstrated by the output).
  • In the third case we pass two instances to method2, inside of which we assign the reference associated with the first argument to the second argument and then make changes using the second argument. Again both point to the same thing, but the assignment is local to the method. When we return dataInst3 is still points to its original object --- Why is this? When we pass an object reference we pass an address where the object in question is stored. This address is the actaul aparmeter that is passed, inside the called method (method2) this parameter acts as a local variable. Any changes made to it last for the duration of the method, when we return from the method (like in call be value) the original value (address) is reinstated.

If in the above case the intention was that dataInst3 should refer to the same object as dataInst1 then the appropriate assignment should have been made before the call to method2.

// Data class
// Frans Coenen
// Thursday 15 July 1999
// The University of Liverpool, UK
      
class Data
{
    // --------------- FIELDS ------------------
    
    private int number1;
    private int number2;
    
    // --------------- CONSTRUCTORS ------------------
    
    public Data(int n1, int n2) {
    	number1 = n1;
	number2 = n2;
	}
		
    // --------------- METHODS ------------------

    /* MAIN METHOD: */
    
    public  void changeValues() {
        number1 = number1+1;
	number2 = number2+2;
	}
	
    public  void outputValues(String name) {
        System.out.println(name + ": number1 = " + number1 + ", number2 = " + number2 + ".");
	}
    }

Table 2: Data class

// CALL BY VALUE APPLICATION
// Frans Coenen
// Thursday 15 July 1999
// The University of Liverpool, UK

import Data;
      
class CallByRefApp
{
	
    // --------------- METHODS ------------------

    /* MAIN METHOD: */
    
    public static void main(String[] args) {
        Data dataInst1, dataInst2;
	Data dataInst3 = new Data(0,0);
        
	// create an instance dataInst1 of the class data
	
	dataInst1 = new Data(1,2);
	
	// Ca1l to method 1 
	
	System.out.println("METHOD 1: Before call by reference");
	dataInst1.outputValues("dataInst1");
	method1(dataInst1);
	System.out.println("METHOD 1: After call by reference");
	dataInst1.outputValues("dataInst1");
	
	// Assign first instance ref to second ref
	
	dataInst2 = dataInst1;
	
	// Ca1l to method1 again 
	
	System.out.println("\nMETHOD 1 (copy opf original instance):\nBefore call by reference");
	dataInst1.outputValues("dataInst1");
	dataInst2.outputValues("dataInst2");
	method1(dataInst1);
	System.out.println("METHOD 1: After call by reference");
	dataInst1.outputValues("dataInst1");
	dataInst2.outputValues("dataInst2");
	
	// Ca1l to method2
	
	System.out.println("\nMETHOD 2: Before call by reference");
	dataInst1.outputValues("dataInst1");
	dataInst2.outputValues("dataInst2");
	dataInst3.outputValues("dataInst3");
	method2(dataInst1,dataInst3);
	System.out.println("METHOD 2: After call by reference");
	dataInst1.outputValues("dataInst1");
	dataInst2.outputValues("dataInst2");
	dataInst3.outputValues("dataInst3");
	}
	
    /* METHOD 1: Change values of data instance */
    	
    public static void method1(Data dataInst) {
    	dataInst.changeValues();	
        }

    /* METHOD 2: Make copy and then change values of data instance */
    	
    public static void method2(Data dataInstX, Data dataInstY) {
        dataInstY = dataInstX;
    	dataInstX.outputValues("\tdataInstX");
	dataInstY.outputValues("\tdataInstY");
	dataInstY.changeValues();	
	dataInstX.outputValues("\tdataInstX");
	dataInstY.outputValues("\tdataInstY");
        }			
    }

Table 3: Application class




Created and maintained by Frans Coenen. Last updated 10 February 2015