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?

Katie
  • 2,594
  • 3
  • 23
  • 31

1 Answers1

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;  
}
Community
  • 1
  • 1
Filipp Voronov
  • 4,077
  • 5
  • 25
  • 32