In C, array is sequence of variables.
int arr[3];
if arr is 2000 then arr+1 is 2000+sizeof(int).
lly arr+2 is 2000+2*sizeof(int).

in that way array elements are accessed but in JAVA array elements are dynamically allocated using new. then how all others variables are accessed, means I want to ask the memory diagram(arrangement) for the arryas.
int arr[]=new int[3].
if arr is 2000 then (arr+1) may or mayn't be (arr+sizeof(int)) as dynamically allocated, then how that variable is accessed?

Recommended Answers

All 3 Replies

int arr[]=new int[3].

arr is a reference variable (like a pointer, but more like a handle) that holds a reference to an array of 3 ints that is allocated on the heap. In c terms, Java's someType varName is more like C's someType *varName. If its a local variable or parameter arr will be on the stack. If its a class variable it will be part of all the class' or instance's data somewhere on the heap, and can only be accessed using a reference to the class or instance.
arr[0] is a refereence to the first element of the array referenced by arr
arr[1] is a reference to the second element of the array refernced by arr
etc

as I know , java dosen't work on pointers.
and whats there local variable in JAVA...???

if array elements are stored in a heap then how to access the next element means how compiler gets the reference of another array indices..how it searches..?

Java does have pointers, of a kind, but you can't manipulate them. Whenever you declare a variable of type Object or array the variable holds a reference, not an Object or array. That's like a pointer.
int[] arr = new int[3];

arr is a reference to the array object. The Java runtime uses that reference to get the actual address of the array on the heap. It knows how big each element is, so it knows how many bytes to add to get to the n'th element.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.