Parameter Passing

Chapter: Methods
...Section: Parameter Passing

Java passes parameters by value.


Exercise 6

Compile and run Ex2.java. Is that the output you expect? Can you think of a way to let foo() modify the caller's data?

It is possible to get the effect of passing by reference. Look at Ex3.java.


Exercise 7

Create a class DangerousFloat. Create a public class Swopper with a swap method that, when called from this main method:
DangerousFloat x = new DangerousFloat(2.0);
DangerousFloat y = new DangerousFloat(3.0);
Swapper s = new Swapper();
s.swap(x,y);
System.out.println("x is "+x.getVal()+" and y is "+y.getVal());
produces the output
x is 3.0 and y is 2.0


You can also get the effect of pass by reference if you pass an array. Java does not wish to copy the entire array in order to pass a value to a method. Look at Ex4.java.


Exercise 8

Write a program with a method swap(int x[]) to swap the first two members of the array. It should work as indicated below:
public class Ex4 {

  public static void main(String[] args) {
    int x[] = {2,3};
    Ex4 thing = new Ex4();
    thing.swap(x);
    System.out.println("x is now {"+x[0]+","+x[1]+"}");
  }
}

java Ex4
x is now {3,2}



rhyspj@gwu.edu