Passing by value or by reference

Passing by value or by reference #

Definition. Imperative languages differ in the way arguments are passed to methods/functions. Two common strategies are:

  • passing by value: the method receives as input a copy of each argument.
  • passing by reference: the method receives as input a reference to each argument (which lets the method modify the originals).

Example. Consider the following program (in pseudocode):

myInteger = 0
myMethod(myInteger)
print(myInteger)

myMethod(argument){
  argument += 1
}
  • If the argument is passed by value, then the program prints 0.
  • If the argument is passed by reference, then the program prints 1.

In Java #

Java (and many other programming languages, like C, Python, Javascript, etc.) passes arguments by value.

Example (continued). The example above translated into Java prints 0.

Warning. Consider a method with a reference type argument. Because Java passes by value, this method will receive a copy of this argument. But this is a copy of the reference, not a copy of the object itself.

Recall the class City seen in the previous section.
What does the following print?

  int myInteger = 0;
  City myFirstCity = new City("Florence", 50100, "Tuscany");
  City mySecondCity = new City("Mantua", 46100, "Emilia-Romagna");

  myMethod(myInteger, myFirstCity, mySecondCity);

  System.out.println(myInteger);
  System.out.println(myFirstCity.zipCode);
  System.out.println(mySecondCity.zipCode);

 public void myMethod(int integer, City firstCity, City secondCity){
    integer += 1;
    System.out.println(integer);

    firstCity.zipCode = 20590;
    System.out.println(firstCity.zipCode);

    secondCity = new City("Rome", 00100, "Lazio");
    System.out.println(secondCity.zipCode);
 }

In the exercise above:

  1. Does the method myMethod have side effect(s)?
  2. If so, then which instruction(s) in this method have side effect(s)?