0

I have a question regarding the address of arrays. Lets says we have this piece of code:

main(){  
int[] numbers = {1, 2, 3};  
method(numbers);  
}  

method(int[] methodNumbers){  
methodNumbers= new int[methodNumbers.length];   
return methodNumbers;  
}

Here's what I think I know. Please correct me if I'm wrong.

So I know there is the main stack frame, method stack frame, and the heap. In our main, the int[] numbers is stored. It is pointing to an address in the heap which is where the indexes are stored. We pass the int[] numbers into the methodNumbers parameter so now they are pointing to the same location in the heap. Inside our method, we declare a new int for our methodNumbers so now the int[] methodNumbers array is pointing to a new location in heap. But in the end we return the methodNumber.

My question is where is the int[] numbersArray pointing to at the end. Is it pointing to the same place or is it pointing to the same location as methodNumbers?

2
  • There is no int[] numbersArray in the code you provided Commented Oct 18, 2016 at 20:44
  • numbers points to the same object as before the call of the method. Commented Oct 18, 2016 at 20:48

1 Answer 1

2

Java is pass-by-value language, so you can't change value (=reference(!) in case of arrays) of variables passed as parameters (but you can change what they refer to).

main(){  
  int[] numbers = {1, 2, 3};  
  method(numbers); //returns pointer to new array created in the method; it's unused

  //here numbers is unchanged, because changing parameter variables
  //in method doesn't change variables outside the method
}

method(int[] methodNumbers){  
  methodNumbers= new int[methodNumbers.length];
    //methodNumbers is a variable local to method,
    //you can change it without interfering with other
    //variables outside the method; but if you change
    //value it referring to (for example via methodNumbers[0] = -1)
    //you will change array you created before method

  return methodNumbers;  
}
Sign up to request clarification or add additional context in comments.

Comments

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.