Please Explain this Java Array Reference Parameter Passing Behavior

后端 未结 4 1476
无人及你
无人及你 2021-01-20 15:02
public class TestArray {
    public static void main(String[] args) {
        int[] ar = {1,2,3,4,5,6,7,8,9};

        shiftRight(ar);
        for (int i = 0; i <         


        
4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 15:22

    In Java, it's a misnomer to say that objects are passed by reference. It's more accurate to say that the reference to the object is passed by value.

    You pass the array reference to reverseArray by value. The local parameter is a copy of the reference to the array. Later when you say

    ar = temp;
    

    You have only pointed the local ar to temp, not the original array reference ar from main.

    On the other hand, in the shiftRight method, you have directly accessed the array through the copied reference, so the original array's contents change and the method works as expected.

提交回复
热议问题