Why is the output of these two java programs different
public class Test {
public static void change(char[] a){
a[0] = '1';
a[1] = '2';
}
public static void main(String args[]){
char[] a = new char[]{'a','b'};
change(a);
System.out.println(a);
}
}
Gate 12
public class Test {
public static void change(char[] a){
a = new char[]{'1','2'};
}
public static void main(String args[]){
char[] a = new char[]{'a','b'};
change(a);
System.out.println(a);
}
}
Conclusion: ab. I understand that I am missing something about how java passes method arguments. I understand that object references are passed by value. However, I cannot reconcile what I understand with the results of these programs.
source to share
In version "2" the change method "does nothing" because you are assigning a new array a
, which is a local (parametric) variable a
. This does not affect the array assigned to the variable a
declared in the main method.
The new array is out of scope and is not available (and therefore intended for garbage collection) when the method change()
exits.
source to share
First you change the array that is passed in and referenced by 'a'
second, you change that array that is referenced by 'a'
the second one you do
char[] original = new char[]{'a','b'};
// this is basically what your function call is doing from here....
char[] a = original; // a is now also referencing the ab array
a = new char[]{'1','2'}; // now a is referencing a 1 2 array.
// then the function returns....and original is the same still
so a is referring to the new array while the original is referring to the original array yet
source to share
This is due to the way you transfer data. In the first example, the array changes because you pass the Change () method to the address of the array, and the method changes the data in the address.
In the second example, the IS array was passed, however you are initializing a new array that declares a new memory space and changes the address that was passed. This, however, does not remove the original declared and initialized instance of char [] in the main method, so when you print it, it prints the local char [], not the new one you were trying to create.
source to share
Because Java passes objects between methods by value and not by reference . In the first example, you instantiate an object in the main and pass it to change
, which only modifies it by setting values. In the second example, you are actually restoring it to change
(using new
) after you created it once in the main. The scope recovered char[]
in change
will be a method only when you go back to the main that called it, it will go back to its own instance, not the one used locallychange
source to share