1

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.

1
  • 13
    If you had tried this out for yourself, you'd have found that int a[10]; is invalid syntax. -1. Commented Nov 5, 2011 at 15:11

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The array size is determined when the array is created, not when the variable is declared. I suppose whether that means it is "fixed after declaration" depends on whether "after declaration" means "immediately after declaration" or "at some time after declaration, maybe".
2

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.

Comments

1

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.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.