Primitives and Objects in Memory

In Java there are seven primitive types; byte, short, int, char, float, double and boolean. Any type which is not in these seven is an Object type. Object types are constructed and stored differently compared to the primitive types. The literals (values) of primitive variables are stored in the location which the variable points to.

To understand this concept better, let us take the example of the statement byte a = 10 as shown in the figure below.

In this statement you have a variable 'a' declared and is initialized with the literal value of 10. When this statement is executed, the OS finds a memory location with the address @8a7d67c and saves the binary value of 10 which is 00001010 and keeps this memory location mapped to variable 'a'

Whenever a reference is made to this variable 'a', the program fetches the value 10 stored by using the memory location mapping.

image alt text

In case of objects however, the memory location does not contain the literals that the object hold. Instead it contains the memory location of the object's literal values. In the example above an array for holding two integers is declared and initialized with values as shown below:

bylte[] myInts = {1,2}

Arrays are objects in Java. From the above figure you see that the memory address - @9a7d59b is mapped to the variable myInts. However the value that this memory location contains is the value of another memory location @69b8b810 and if you look into what is stored in this memory location, you will see the binary representation of literals 1 and 2.

Note however that the memory addresses that are shown here are only for representation and in reality these values will be different for different machines and you cannot know which memory address is assigned to which variable before hand. Once assigned however, you can see the address of the objects if you try to print the object as shown in the example. When you print 'a' you see the literal value 10 printed out. However when you print myInts you will see the memory address of the Array where the literals are stored.

In case of an Array, all the literal values of the array are stored in a contiguous memory and the location that is printed out is the starting address of the contiguous memory.

results matching ""

    No results matching ""