本文发表在 rolia.net 枫下论坛Let me try to explain this quiz
Here are premises:
1) This example is designed a little bit confusing--- All of its Arrays have only one element.
2) An int like x=7 is an int, not an Object. Once an int is put into an Array, that Array
is an Object--- of course, an Object (Array) containing the int.
3) In normal cases, Java passes Object by reference. (In RMI, it can pass by value).
Now let's come to the quiz itself.
1) As JVM loads example class, i[], which is an instance varaible, is initialized to {0} in the JVM;
2) JVM finds main() method in example class and executes it. Now i[] is pointed to another Array
{1} in the JVM.
3) Executes change_i(int i[]). This is where confusion may arise. What is passed into the method
call is "a copy of the reference of i[]". In the execution, this copy is directed to j[].
Eventually, this copy is pointed to {2} in the JVM.
4) Reminder: change_i just manipulates on " that copy of the reference of i[]".
5) As change_i is finished, that "copy of reference of i[]" is out of scope. It is gone. But, but, but, ..... but this does no harm on the original i[], which still points to {1} in the JVM.
6) Now we come to the conclusion that System.out will show us number "1".
7) That's it.更多精彩文章及讨论,请光临枫下论坛 rolia.net
Here are premises:
1) This example is designed a little bit confusing--- All of its Arrays have only one element.
2) An int like x=7 is an int, not an Object. Once an int is put into an Array, that Array
is an Object--- of course, an Object (Array) containing the int.
3) In normal cases, Java passes Object by reference. (In RMI, it can pass by value).
Now let's come to the quiz itself.
1) As JVM loads example class, i[], which is an instance varaible, is initialized to {0} in the JVM;
2) JVM finds main() method in example class and executes it. Now i[] is pointed to another Array
{1} in the JVM.
3) Executes change_i(int i[]). This is where confusion may arise. What is passed into the method
call is "a copy of the reference of i[]". In the execution, this copy is directed to j[].
Eventually, this copy is pointed to {2} in the JVM.
4) Reminder: change_i just manipulates on " that copy of the reference of i[]".
5) As change_i is finished, that "copy of reference of i[]" is out of scope. It is gone. But, but, but, ..... but this does no harm on the original i[], which still points to {1} in the JVM.
6) Now we come to the conclusion that System.out will show us number "1".
7) That's it.更多精彩文章及讨论,请光临枫下论坛 rolia.net