Pass-by-value vs Pass-by-reference

When a parameteris passed into a method, it can be passed by value or by reference.

Pass-by-value copies the value of an argument into the parameter. Changes made to the parameter have no effect on the argument.

Pass-by-reference passes a reference to the parameter. Changes made to the parameter will affect the argument.

When a simple primitive type is passed to a method, it is done by use of call-by-value. Objects are passed by use of call-by-reference.

The following program uses the "pass by value".

 
class Test {
  void change(int i, int j) {
    i *= 2;
    j /= 2;
  }
}
public class Main {
  public static void main(String args[]) {
    Test ob = new Test();

    int a = 5, b = 20;

    System.out.println("a and b before call: " + a + " " + b);

    ob.change(a, b);

    System.out.println("a and b after call: " + a + " " + b);
  }
}

The output from this program is shown here:


a and b before call: 5 20
a and b after call: 5 20

In the following program, objects are passed by reference.

 
class Test {
  int a, b;
  Test(int i, int j) {
    a = i;
    b = j;
  }
  void meth(Test o) {
    o.a *= 2;
    o.b /= 2;
  }
}
public class Main {
  public static void main(String args[]) {
    Test ob = new Test(15, 20);

    System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b);

    ob.meth(ob);

    System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
  }
}

This program generates the following output:


ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.