Java and pass-by value

Java uses the pass-by value.

Java copies and passes object reference by value too, not the object. With a copy of the object reference, a Java method can manipulate the mutable fields of the object (see example 1 below), but a Java method can NOT change the original reference (see example 2 below).

Example 1:

public void mutate(MyObject arg1) {
arg1.field1 = new_value;
}

The code above will change the field 1 of MyObject.

Example 2:
public void swap(MyObject arg1, MyObject arg2) {
arg1 = arg2;
}

public void callee() {
myObj1.field1 = value_1;
myObj2.field1 = not_value_1;
swap(myObj1, myObj2);
// myObj1.field1 would still hold the value of “value_1″.
}

A good reference document can be found in one of the JavaWorld article published in the year of 2000. “Does Java pass by reference or pass by value?”

Follow

Get every new post delivered to your Inbox.