-1

How much bytes of memory are allocated after the following java statement is executed using a 32 bit JVM (assume that a memory reference contains only the first address of location being referenced)?

int a = new int[20];
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
  • It looks like Java, why did you tag it javascript? These are two very different languages. – Alex Pakka Dec 13 '13 at 18:37
  • 1
    What does your textbook say about memory allocation? – Mike Manfrin Dec 13 '13 at 18:37
  • Exactly zero bytes are allocated because that code will never compile in java. – DwB Dec 13 '13 at 18:40
  • An int is 4 bytes, so you've got 80 bytes to start with. Then the object overhead, which varies with JVM but is probably 48 bytes. Then the whole allocation is apt to be rounded up to a "boundary" of 16 or 32 bytes. – Hot Licks Dec 13 '13 at 18:40
  • 1
    a primitive array is just a reference, so no object overhead... right? – SnakeDoc Dec 13 '13 at 18:41
  • @SnakeDoc - In Java a primitive array is a full-fledged Java object. – Hot Licks Dec 13 '13 at 18:42
  • the OP means `int[] a = new int[20];` which would be the size in bytes of an `int`, which in java is 4 bytes. So 4 bytes * 20 array elements = 80 bytes as others have mentioned. – SnakeDoc Dec 13 '13 at 18:42
  • @SnakeDoc - Plus object overhead, plus rounding. – Hot Licks Dec 13 '13 at 18:43
  • @HotLicks seems the only way to find out for sure the exact overhead would be to profile some basic code creating arrays of ints. – SnakeDoc Dec 13 '13 at 18:44
  • (Think about it: You can ask a Java array for its size, so that must be included somehow. You can query it's type, so that must be included. It's garbage-collected, so there must be the necessary bits in the header for that.) – Hot Licks Dec 13 '13 at 18:44
  • Well, you could always examine the code in the JVM. But of course there's no guarantee that two different JVMs, even Sun/Oracle ones, do it the same. – Hot Licks Dec 13 '13 at 18:45
  • what does the JLS say about int arrays? i suppose you are right about being able to call `array.length`, and that has to be either stored someplace, or calculated from somewhere. – SnakeDoc Dec 13 '13 at 18:47

2 Answers2

2

80 bytes for the array itself (4 bytes for an int in a 32-bit system/jvm). Not sure about the variable. But you have numerous problems. One, you're assigning an int array to an int--that won't compile. Two, your question's lone tag is for javascript, which makes me assume that you don't know that javascript and java are different, which makes me wonder why you're concerned with memory allocation at the primitive level at this point in your educational journey.

Brian Warshaw
  • 22,657
  • 9
  • 53
  • 72
2

The int(s) use 4 * 20 bytes. The OpenJDK/Oracle JVM, the header uses 12 bytes, but objects have an 8 byte alignment.

So the total memory used would be 96 bytes.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130