| Author |
passing by reference
|
Vidya Krishnamurthi
Greenhorn
Joined: Jan 12, 2003
Posts: 18
|
|
class I { private String name; public String name() {return name;} public I(String s) {name = s;} } class J { public static void m1(I i) {i = null;} public static void main (String[] args) { I i = new I("X"); // 1 m1(i); // 2 System.out.print(i.name()); // 3 } } Which of the following are true statements and which of the following could be a result of attempting to compile and run the program? a. The object created a line 1 is eligible for garbage collection after line 2. b. A NullPointerException is generated at line 3. c. Prints X. d. Compiler error. e. None of the above ans is c I thought it was passed by reference when u do i=i Can any one please explain Thanks in advance..
|
 |
G Nadeem
Ranch Hand
Joined: Apr 25, 2003
Posts: 48
|
|
Hi Vidya, this is how i will interpret it.... a copy of the reference to object I is passed to the method 'm1'. so the local variable 'i' of the method 'm1' points to object I at line 1. now if we do any operation directly on 'i' like i.aMethod(), it will effect I object (I being object and not a primitive). however if the reference i is changed to point to someother object/null (using = operator), the orignal reference i at line 1 will not be effected. since 'i' in method 'm1' is local variable of 'm1'. [ June 04, 2003: Message edited by: G Nadeem ]
|
 |
Brian Joseph
Ranch Hand
Joined: May 16, 2003
Posts: 160
|
|
|
Key: A "copy of the reference" (not the object of course) is passed. I think of reference variables as holding some type of address value which refers to the object in memory. A copy of that address is passed to the method parameter. The method parameter itself is a unique variable.
|
 |
 |
|
|
subject: passing by reference
|
|
|