1

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.

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks. But if I change the array in the goal method/class , the original array will stay the same. doesn't it mean additional memory usage?
Thanks, for my need, the goal methods or classes do not need to change the variable, only reading is enough. What would be your suggestion?
You can pass it without problem and no additional memory is needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.