Search This Blog

Thursday, April 18, 2013

OOPJP(SCJP) Pass by reference or Pass by value?


public class PassByReference {

public PassByReference() {
List<String> list = new ArrayList<String>();
list.add("one");
addToList(list);
System.out.println(list.size());
}
private void addToList(List<String> myList) {
myList.add("two");
myList = null;
}
public static void main(String[] args) {
new PassByReference();
}
}

What is the output?
a. NullPointerException
b. 1
c. 2
d. 0

Answer : c
Primitive types are always passed by value. 
When it comes to object references also it is pass by value as in, the address of the object is copied into the method argument. As long as you manipulate the object reference using its exposed API, changes made will be reflected everywhere. Modifying the reference variable or the variable holding the address will not have any effect on the object.


OOPJP(SCJP) Pass by reference or Pass by value?SocialTwist Tell-a-Friend

1 comment:

  1. Very informative OOP's concepts. I always learn its concepts from Car towing service but you have also define it nice. Thanks for sharing.

    ReplyDelete