• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array and memory size. How JVM know?  RSS feed

 
Ivan Franko
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For example,

I write this code:



And I understand this code some like this:

Allocate memory for 10 Objects.

Next step,

I write code:



I added in array different objects and if I understand correctly different obj's has different size.

In this case, how JVM know how much memory allocated on the first step???
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple - the Object[] only stores references to the objects, not the actual objects. There is no limit on the size a reference should be in memory, but within a JVM it's always the same no matter the type of object reference. That is, a String reference variable will require just as much memory as an Object reference variable or an ArrayList reference variable.
 
Ivan Franko
Ranch Hand
Posts: 46
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Spoor, great thanks!

and i find answer in "Thinking Java" too:

....arrays of objects hold references, but arrays of primitives hold the primitive values directly.


 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Correct. But since the size of all primitives* are always the same the size of arrays in memory can be calculated.

* For boolean there is no requirement on how much memory it requires internally (the requirement is only for the serialized form), but any JVM implementor will use the same size anyway. Whether that's 1 byte, 1 int or 1 bit is irrelevant.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!