From javaprepare.com, questions on Language Fundamentals: What happens when the following program is compiled and run? Select the one correct answer.
The correct answer is "The program prints 1". Why is this so? An array is an object, so when it's passed into a method, the actual reference is modified, not a copy, right? If so, the answer should be "The program prints 2". At least that's what I think.
You can change what the parameter "i" in change_i() points to without having any effect whatsoever on the local variable "i" in main(). If you changed the elements of the array passed in as an argument, then you'd effect main. If you just change the parameter, this is a separate variable from the one in main and so there's no effect. Ponder this: "References are passed by value."
This is a trivially modified version of the same program which does print "2" :
public class example { int i[] = {0}; public static void main(String args[]) { int i[] = {1}; change_i(i); System.out.println(i[0]); } public static void change_i(int i[]) { i[0] = 2; } }