I've learned that in Java, arrays are passed by reference, meaning that they can be modified within functions. However, I recently came across this piece of code that confused me, because it seems to show inconsistent behavior.
import java.io.*;
import java.util.*;
public class TestProgram {
public static void fMethod(int[] f){
f[0] = 9;
f[1] = 7;
f = new int[4];
}
public static void main(String[] args){
int[] fParam = new int[3];
fMethod(fParam);
System.out.println(Arrays.toString(fParam)); // prints [9, 7, 0]
}
}
Because the function fMethod()
seems to reset f to a new int[4]
at the end, I expected to see [0, 0, 0, 0]
printed to the console. However, it seems that only the f[0] = 9
and the f[1] = 7
lines were actually executed, while the last line was ignored. I find this strange. Can somebody please point me in the right direction?