Why is this pass by reference? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
27th Aug 2019, 2:07 AM
你知道規則,我也是
你知道規則,我也是 - avatar
3 Answers
+ 13
According to what I've read a while ago, everything in Java is pass-by-value. What happens when an object is passed, is that a reference to the object is passed by value, to the method. This means that yes, you can alter the individual values in that particular array and have your changes reflect in the array residing in main as in your example, but if you do: public static void incValue(int[] i) { i = new int[3]; } you'll realize that this doesn't work because you are trying to alter the reference itself (which was passed by value) to point to a new array. This change will not be reflected by your array in main. A "true" pass-by-reference would allow this to happen.
27th Aug 2019, 2:19 AM
Hatsy Rei
Hatsy Rei - avatar
+ 1
In fact, JAVA doesn't support pass arrays by value. And this is common (I guess) with majority of programming languages. The reason is that an array is a pointer to a location in memory, like C or C++. But has its own mechanism for outbound check and other managed stuff. If you don't want the original array to be modify inside the function, you had to make a copy of the array, or coding in some way you don't need to change the values of the array.
27th Aug 2019, 9:39 AM
Benjamin Alejandro Luna
Benjamin Alejandro Luna - avatar
- 1
so then instead public static void incValue(int[] i) { i = new int[3]; } you can do public static void newValue(int[][] i) { i[0] = new int[]{1,2,3}; } public static void main(String[] args) { int[][] var = { {4,5,6} }; newValue(var); System.out.print(var[0][0]); }
27th Aug 2019, 3:03 PM
zemiak