Phoenix
Phoenix

Reputation: 8923

What does this statement mean in Java?

Suppose there is an array declaration:

int [] a = new int[3]; 

I'm reading a book that says the reason we need to explicitly create arrays at runtime is because we cannot know how much space to reserve for the array at compile time. So, in this case above don't we know we need to reserve 3 times the size of int of the underlying java platform ?

Upvotes: 0

Views: 146

Answers (5)

Lawryenzo
Lawryenzo

Reputation: 1

In your case the size of the array is 3.The number inside the square brackets is the size.CHeck this weeks tutorial about arrays on www.codejava.co.uk

Upvotes: 0

Frank Sposaro
Frank Sposaro

Reputation: 8531

Yes. Your correct.

3 * sizeOf(int) + array overhead.

You are reserving that much memory and then handing a pointer to the first position to your variable a. Then a can figure out how to index the array based on the location and size of what is being stored.

Upvotes: 0

Idan Arye
Idan Arye

Reputation: 12603

Are you sure that book you are reading is about Java?

Unlike C/C++, Java does not have that dilemma - arrays are always allocated at runtime, even if you know their size during compile time.

Upvotes: -2

Jon Skeet
Jon Skeet

Reputation: 1500535

So, in this case above don't we know we need to reserve 3 times the size of int of the underlying java platform ?

Well actually slightly more than that - because arrays are objects with a class reference, as well as the length.

But yes, in this case you happen to know the size in advance. But Java also lets you write:

int[] a = new int[getLengthFromMethod()];

... in which case no, the amount of memory won't be known at compile time. This flexibility makes it considerably simpler to work with arrays than if you had to know the size at compile time. (Imagine trying to make ArrayList work otherwise, for example.)

But bear in mind that memory allocation is very dynamic in Java in general - it's effectively only really the size of stack frames which is known in advance, and then only in relative terms (as the size of a reference can vary between platforms). All1 objects are allocated on the heap and references are used to keep track of them.


1 Okay, aside from smart JVMs which are sometimes able to allocate inline after performing escape analysis.

Upvotes: 5

Razvan
Razvan

Reputation: 10093

In that book it probably says that there are scenarios in which you don't know at compile time how large an array will be (e.g.: when you ask a user for a set of numbers you don't know how many numbers he will insert).

In your example (int [] a = new int[3]) you obviously know the size of the array at compile time; it's 3.

Upvotes: 2

Related Questions