Rule: Chap 10, JLS: In the Java programming language arrays are objects (�4.3.1), are dynamically created, and may be assigned to variables of type Object (�4.3.2). All methods of class Object may be invoked on an array. when you pass a reference of an object to another method, you pass a reference to a copy of that object
this must work for arrays too in the same way. (we'll get a rancher to correct me soon when the US wakes up) Marcus :roll:
Hi, I *think* the reason its 1 is because i is passed to change_i by reference as opposed to by value. Therefore while i = 2 in the method change_i, in the method main, it remains i = 1. If you wanted to "permanently" change the value to 2, you would type i = 2; in change_i (as this would be accessing the object directly rather than the reference) This is my understanding, which I admit might be completely wrong, so please feel free to correct me. Mick
What got passed into change_i is a copy of the reference to the array. Inside the method this reference is changed. As a result it no longer refers to the original array, i. This reference goes out of scope and (is this right)the array referred by it becomes ready for garbage collection when method change_i completed, and has no bearing on the array i in main the argument of change_i was just a copy of the reference, not the actual reference itself. hope this is clear
Then why when I use i=2 instead of i=j in change_i(), i in main gets changed to 2? Thanks, Jenny
Because, initially, the parameter i in the method change_i references the same array as the array i in the main method. If you modify the contents of the i in change_i, you'll be modifying the contents of the array i in main. If, however, you modify the reference to i in change_i directly, as done in the original example, the i in change_i and the i in main will no longer reference the same array. Take a look at this code:
You can see that, until we change the local variale i, in line 1, we can modify the original array (a) from main. However, after line 1, we can not do that. I hope that helps, Corey
Hiya Fellow Ranchers ! Believe it or not ! I was about to post this very question before I decided to go through the latest five in this forum.... and guess what ! My question had already been posted... Such is the greatness of this site ! Excellent explanation Corey... it all became clear after reading your explanation.