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);
}
}
The output is 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);
}
}
The output is ab. I understand I am missing something about the way java passes method arguments. I understand references to objects are passed by value. However, I cannot reconcile what I understand with the results of these programs.
In version “2”, the change method “does nothing”, because you are assigning a new array to
a, which is the the local (parameter) variablea. This has no effect on the array assigned to variableadeclared in the main method.The new array goes out of scope and is inaccessible (and thus earmarked for garbage collection) when the
change()method completes.