There are two ways we can pass an argument to a method.
Java uses call-by-value to pass all arguments.
BUT the effect is different between a primitive type or a reference type.
When passing a primitive type to a method, it is passed by value.
A copy of the argument is made, and updating the parameter has no effect outside the method.
// Primitive Types are passed by value. class Test {// ww w. j av a 2s . co m void meth(int i, int j) { i = 2; j = 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } }
When passing an object to a method, the reference to objects are passed. It is still a pass-by-value. BUT it is the reference value passed.
When we create a variable of a class type, we are only creating a reference to an object.
Changes to the object inside the method do affect the object used as an argument.
You can think the reference as the room key. When passing object to a method the key is duplicated so we can still open the room with the duplicated key.
For example, consider the following program:
// Objects are passed through their references. class Test {/* w w w . ja v a2 s. c o m*/ int a, b; Test(int i, int j) { a = i; b = j; } // pass an object 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); } }
When an object reference is passed to a method, the reference itself is passed by use of call-by-value.
The copy of that value is still referring to the same object.
Passing arrays and individual array elements to methods.
import java.util.Arrays; //ww w. j a v a 2 s.co m public class Main { // main creates array and calls modifyArray and modifyElement public static void main(String[] args) { int[] array = { 1, 2, 3, 4, 5 }; modifyArray(array); // pass array reference System.out.println(Arrays.toString(array)); modifyElement(array[3]); // attempt to modify array[3] System.out.println(Arrays.toString(array)); } // multiply each element of an array by 2 public static void modifyArray(int array2[]) { for (int counter = 0; counter < array2.length; counter++) array2[counter] *= 2; } // multiply argument by 2 public static void modifyElement(int element) { element *= 2; System.out.printf("Value of element in modifyElement: %d%n", element); } }