From what I know, local vars and args are stored in the Stack Memory, which includes object references, whereas actual objects are stored in the heap memory. So what exactly happens when you use var-args ?
public static int[] test(int... x) {
return x;
}
public static void main(String[] args) {
int[] a = test(1,2,3,4,5);
int[] b = test(6,7,8,9,0);
System.out.println(a);
System.out.println(b);
for (int i : a) {
System.out.println(i);
}
for (int i : b) {
System.out.println(i);
}
Here I believe that all the values passed as params to test
in x
are stored on the stack, hence when we call test(1,2,3,4,5)
, we are using up stack space, correspondingly when we call test(6,7,8,9,0)
we should be causing memory collision on the stack... but when I run the above, I get the following result.
[I@2db0f6b2
[I@3cd1f1c8
1
2
3
4
5
6
7
8
9
0
As can be seen, there is no corruption of items in a
due to the 2nd call to test
which generates b
. Both seem to be stored differently.
Does this mean that the params are somehow stored on the heap? Would this mean that any call of the form function(param)
translates to the value of param
(primitive or memory reference) not necessarily lying on the stack memory?