Home > database >  Explanation of Arrays in Java and modifying outside of scope?
Explanation of Arrays in Java and modifying outside of scope?

Time:03-08

I am confused why the hello method is able to affect the array declared in the main method. My understanding was it was outside of the scope.

public class Test {
    
    void hello(String i, int[] arr){
        i  = "hello";
        arr[0] = 4;
    }
    
    public static void main(String args[]){
        Test t = new Test();
        String i = "hey";
        int [] arr = {0,1,2,3};
        t.hello(i,arr);
        System.out.println(i);
        System.out.println(Arrays.toString(arr));
    }
}

returns

hey
[4, 1, 2, 3]

i would understand a return of "heyhello" or [0,1,2,3].

CodePudding user response:

There's an important difference between String and int[].

Both are so-called "reference objects", meaning that they hava a unique identity, and can be referenced from variables, fields, method arguments etc.

So, t.hello(i,arr) passes two arguments into the hello() method:

  • a reference to a String with content "hey"
  • a reference to an int[] array with content {0,1,2,3}.

Inside hello(), you "modify" both variables, but differently:

  • With i = "hello";, you append a word to the end of the string. The Java designers decided to make strings "immutable", so you can't change a String object that has been created, you can only create a new string in such a case. That means that the original string (that the i variable from main() still references) will not be affected. It's only the i inside hello() that now references the fresh, longer string. And main() still has its i being "hey".

  • With arr[0] = 4;, you set the first array element to a different value. Arrays have been defined differently, they are mutable. For an existing array, you can modify its elements without the need for a fresh copy. So, there's still only one array in use, and its first element has been modified. When main() prints its arr array, it is the identical array that has been modified inside hello(), und thus contains the number 4.

CodePudding user response:

The posted code is demonstrating the difference between passing mutable objects and immutable objects as parameters.

The array arr is passed to hello as an argument. That means the pointer to the arr object is copied and the copy is given to hello, so hello has a pointer to the array declared in the main method. Arrays are mutable and hello has a reference to it,, nothing stops hello from changing the contents of arr.

The string i gets passed into hello similarly, hello gets a copy of the pointer. The hello method replaces the string referred to by its copy of the pointer (since strings are immutable), but the pointer used by the main method is unaffected and still points to the original value of i.

  • Related