posted 12 years ago
Ok let me try to explain the concepts behind all of this to you.
Fist example explanation:
When you do this:
int i[] = {0};
You're actually declaring an integer array reference variable (i), constructing an one-element one-dimension array object of integers in memory (the heap) and assigning 0 or initializing the array element with 0.
it's like: int[] i = new int[1]; i[0] = 0;
The array reference variable "i" isn't actually the array object, it is just a reference holding the address of where in memory the created array object is. Reference variables are just variables that can point to objects of a specific type in memory.
When you pass a object reference variable to a method (change_i(i); in the first example) you are passing the object reference (the address of how to get to the object) not the real object and then you assign that address to another reference variable of the same type inside the method. It's like pointing the variable inside the method to the same object the variable outside the method is referring to so you can access the same object with both variables.
That's why when you assign another value or modify the value of the array element by means of the "inside the method reference variable" you can access that element with the reference variable outside the method because both are pointing to the same object in memory (the heap).
Second example explanation:
When you pass primitive variables you are passing a copy of the value of that primitive variable to the method. The variable declared inside the method definition is just a different variable that happens to have the same name as the variable declared outside the change_i method and that gets a copy of the value of the variable passed to it. Whatever modification you do inside the method is to the value of the inside variable.
So the System.out.println(i) is actually printing the variable outside the method which is holding 1.
Try to print i inside the method and you will print out the modification. you an even modify the method to return a int and return the modification and assign it back to the i variable declared outside.
Hope you can get the concepts.