Reputation: 1219
I wanted to know if the Java arrays are fixed after declaration. When we do:
int a[10];
and then can we do:
a = new int [100];
I am unsure if the first statement already allocates some memory and the second statement allocates a new chunk of memory and reassigns and overwrites the previous reference.
Upvotes: 1
Views: 24508
Reputation: 356
Array has fixed length but if you want the array size to be increased after this:
private Object[] myStore=new Object[10];
In normal way you have to create another array with other size and insert again all element by looping through the first array,but arrays class provide inbuild method which might be useful
myStore = Arrays.copyOf(myStore, myStore.length*2);
Upvotes: 1
Reputation: 8295
Array have fixed length that is determined when you create it. If you want a data structure with variable length take a look at ArrayList or at LinkedList classes.
Upvotes: 1
Reputation: 52185
Yes it is:
The length of an array is established when the array is created. After creation, its length is fixed.
Taken from here.
Also, in your question the first scenario: int a[10]
is syntactically incorrect.
Upvotes: 9
Reputation: 181290
The second statement allocates a new chunk of memory, and the previous reference will eventually be garbage collected.
You can see it by yourself using a java debugger. You will notice that a will point to a different location after the second statement executes.
Good luck with your H.W.
Upvotes: 2