Basic Memory Allocation in Java

I see beginners in Java remembering the statements “Objects are passed by reference, primitive datatypes are passed by value”. Well that’s all fine, but it doesn’t really need memorizing once you know the basics of memory allocation (without the type information)

I give a pictorial view (simplified) of execution of some sample code

The standard memory representation is that of heap storage followed by the program stack

memory allocation

int a;

memory allocation for a declared

a = 10;

memory allocation for a assigned 10

String b;

memory allocation for b declared

b = new String();

memory allocation for new object created

The basic method of parameter passing between methods is to “Pass values in stack”, which is equivalent of “Pass variables in stack by value”

Thus a call to foo (a,b) will pass value of a (10) as first parameter, and value of b (reference to heap location) as second parameter. Effectively, the String object gets passed as reference, while primitive datatype a gets passed by value.

This is analogous to passing pointers in C once the pointer is referencing a location created by malloc(). It is just this part that Java (and most other OO languages) implicitly provide for, by use of the keyword ‘new’ (or call to the object constructor)

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.