jd466
jd466

Reputation: 579

Memory usage/ reference in java

I am going to ask a basic question about Java memory usage.

Imagine we have an array List and it is large enough and we don't like to use more memory. Now if I want to pass this array to another methods in this class, or other classes through their constructor or method, do I need additional memory/is there additional memory usage for this array?

If yes, could I just make this array package level, and therefore the other classes in this package could access it directly, without any memory need.

Thank you in advance.

Upvotes: 1

Views: 279

Answers (1)

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26956

No, no additional memory is necessary. The parameter of a function is passed by copy of the reference. It means that for any kind of object only 4 additional bytes are used.


If you pass an array as parameter and you modify it in the body of the method the changes will be exported outside of method.

Instead if you reassign the array variable, the difference is not visible externally.

This happens because the parameters are passed as copy of the reference and not by reference.

public void vsibleModification(int[] a) {
    for (int i = 0; i < a.length; i++) {
        // This change is visible outside of method because I change 
        // the content of a, not the reference
        a[i] = a[i] + 1;  
    }
}

public void nonVisibleModification(int[] a) {
    // Non visible modification because a is reassigned to a new value (reference modification)
    a = new int[2];
    a[0] = 1;
    a[1] = 2;
}

Upvotes: 2

Related Questions