Java Method Argument Passing

Description

When a parameter is 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.

Example

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 {/*from   www.ja v  a2 s  .  c om*/
  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:

Example 2

In the following program, objects are passed by reference.

 
class Test {//w  w w  .j a  v a 2 s .  c o  m
  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:





















Home »
  Java Tutorial »
    Java Language »




Java Data Type, Operator
Java Statement
Java Class
Java Array
Java Exception Handling
Java Annotations
Java Generics
Java Data Structures