Thursday 20 October 2016

c - Memory allocation in Java - Declaration vs Definition



In C, when we declare something, we tell the compiler what type of thing the variable contains. Only during the definition do we allocate memory space for it. However, in Java, memory space is alloated when we declare a variable



int x; // allocates space for an int


Are my premises correct? Does that mean we should be a sparse with decalarations as possible?


Answer



When it comes to variables in Java, there is no separation between declarations and definitions. This does not influence memory allocation process, though.




What happens to memory allocations in Java is close to what happens to allocating memory from the dynamic area (i.e. "the heap") in C. There, defining a variable of pointer type allocates space for the variable itself, but it does not allocate memory for what the pointer points to. Here is an example of a simple string manipulation in C:



// Allocate memory for the pointer
char *str;
// Allocate memory for the string itself
str = malloc(16);
// Copy the data into the string
strcpy(str, "Hello, world!");



Similar things happen in Java when you deal with objects. Defining a variable allocates space for the object reference, but not for the object. You need to call new in order to "attach" that reference to a new object:



// Allocate memory for the reference
String str;
// Allocate memory for the string, and sets data
str = new String("Hello, world!");


Note that this applies only to objects. Primitive types are handled differently, in a way that is a lot more similar to the way the primitives are handled in C.



No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...