0

So this is my code:

File A.java

package test;

import java.util.Arrays;

public class A {

    static int[] test;

    public static void main(String... args) {

        test = new int[2];
        B.function(test);
        System.out.println(Arrays.toString(test));
    }
}

File B.java

package test;

public class B {
    static int[] function(int[] array){
        array[0] = 1;
        array[1] = 2;

        return array;
    }
}

Output: [1,2]

I am not able to understand how exactly does this of code works. I am passing a variable called "test" to a function whose parameter is int[], and parameters are treated as local variables, as far as my understanding goes. So how does a change made to a local variable reflect in the actually passed variable?

hackrush
  • 88
  • 9
  • 1
    What makes you think this is specific to Java 8? (Also everything that is not a primitive data type is passed by reference in Java, so your function is essentially operating on the "original" array you are passing, it's not creating a local copy) – UnholySheep Nov 12 '16 at 20:46
  • 1
    Because arrays are passed by "reference" and not by "value" as in C for example. – Keiwan Nov 12 '16 at 20:46
  • @MickMnemonic I couldn't find the link that you specified earlier, but upon reading it now, it was not entirely clear to me, as it involved a lot of things. Since I am new to this inheritance thing I wanted someone to explain it to me one-on-one. It is less confusing this way. Thank you for understanding. – hackrush Nov 13 '16 at 06:39
  • @UnholySheep I know it is not specific to Java 8. It is just a habit to mention the version as sometimes exclusive libraries are used which are version specific(though not in this case). – hackrush Nov 13 '16 at 06:40

1 Answers1

1

So how does a change made to a local variable reflect in the actually passed variable?

Reference variables are stored locally (in stack memory which is different for each running thread), but all objects (referenced by the reference variables) are managed in the Heap memory by the JVM.

So in your case, array (reference variable) is local to the function method, but the actual object referenced by the array is in Heap memory.

For example, int[] a = new int[10];

This creates an array object (in heap) referenced by variable a (local to method or block). When you pass a to some other method, a copy of the reference variable is created but that copy also refers to the same array object. When you modify anything using the second reference variable it will change the same object on the heap.

You can think like this for simple understanding, An Object is a TV where as Reference Variables are Remotes, so when you do anything with the remote (i.e., using reference variables) it will control the same TV (same object).

Vasu
  • 21,832
  • 11
  • 51
  • 67