Wednesday, May 18, 2011

How are arrays stored in java?

Array in java is on heap, and its reference being on Stack
(Open your eyes c and cpp programmers)
A Java array is quite different from a C++ array on the stack. It is, however, essentially the same as a pointer to an array allocated on the heap.

That is,

int[] a = new int[100]; // Java


is not the same as


int a[100]; // C++


but rather


int* a = new int[100]; // C++


So , take a look at it:


int[] a = new int[] {100, 99, 98}; // "a" references the array object.
int[] b; // "b" doesn't reference anything.

b = a; // Now "b" refers to the SAME array as "a",
//so its a shallow copy
b[1] = 0; // Also changes a[1] because a and b refer to the same array.

No comments:

Post a Comment

Chitika