Java Method Argument Passing

In this chapter you will learn:

  1. What is the difference between pass-by-value vs pass-by-reference
  2. Example - Pass-by-value
  3. Example - Pass-by-reference

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 w w  w . j  a  v  a 2 s .c o m
  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 {/*from   w ww.  java 2 s.c  om*/
  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:

Next chapter...

What you will learn in the next chapter:

  1. What is Java Method Recursion
  2. Example - Java Method Recursion