Examples of Passing Parameters by Value

Call-by-value is the way parameters are passed in Racket, Ruby, and Java. In all cases, we make a copy of the actual argument and bind it to the formal argument --- but for objects or structures, we copy the reference to the object or structure, not the whole object. Here are two examples in Java. These are adapted from The Java Programming Language by Ken Arnold and James Gosling.

We could exhibit the same effect in Racket and Ruby - there is also a separate Ruby example.

Passing a primitive type as a parameter:
class PassByValue {
  public static void main(String[] args) {
    double x = 1.0;
    System.out.println("before: x = " + x);
    halveIt(x);
    System.out.println("after: x = " + x);
  }

  public static void halveIt(double arg) {
    arg = arg/2.0;
    System.out.println("halved: arg = " + arg);
  }
}
Sample output:
before: x = 1.0
halved: arg = 0.5
after: x = 1.0
Here is another example, in which we pass an object as a parameter.
import java.awt.Point;

class PassObject {
  public static void main(String[] args) {
    Point p = new Point(10,20);
    System.out.println("before halveX: p.x = " + p.x);
    halveX(p);
    System.out.println("after halveX: p.x = " + p.x);

    setIt(p);
    System.out.println("after setIt: p.x = " + p.x);
  }

  public static void halveX(Point q) {
    q.x = q.x/2;
    System.out.println("halved: q.x = " + q.x);
  }

  public static void setIt(Point q) {
    q = new Point(0,0);
    System.out.println("setIt: q.x = " + q.x);
  }
}
Sample output:
before halveX: p.x = 10
halved: q.x = 5
after halveX: p.x = 5
setIt: q.x = 0
after setIt: p.x = 5