Tharaka Ratnayake
Tharaka Ratnayake

Reputation: 54

Memory allocation for classes in java

This is a working java code which is used for implementing trie data structure.

class TrieNode {
TrieNode[] arr;
boolean isEnd;
// Initialize your data structure here.
public TrieNode() {
    this.arr = new TrieNode[26];
}

What I don't understand is how the memory allocation works with

TrieNode[] arr;

code. If it were something like this

class TrieNode {
    int[] arr;
    boolean isEnd;
    // Initialize your data structure here.
    public TrieNode() {
        this.arr = new int[26];
    }

I know that this allocates memory for 26 integers. It's better if you can explain how the memory allocation works for first code. (In compiler's perspective)

EDIT : Sorry if my question is unclear.What im asking is we create array with 26 elements in

new TrieNode[26];

How much memory is allocated?

Upvotes: 0

Views: 3086

Answers (2)

user3739478
user3739478

Reputation: 66

Using your first code, When you create object of TriNode like

TriNode t = new TriNode();

JVM will allocate memory to store 26 references for arr elements and 1 reference for isEnd field. To store references , JVM uses 32 bits for a 32 bit JVM and 64 bits for a 64 bit JVM. When you create array

new TrieNode[26];

It will allocate 26*(64bit/32bit)+1 boolean because it doesn't create TrieNode objects instead it creates array of references to store TriNode objects which are not created yet. So when you initialise array elements like

arr[0] = new TrieNode();

Then it will allocate memmory for TrieNode() object and arr[0] will point this object.

So conclusion is JVM will not allocate memory for 26 Trinode objects instead it will allocate memory for their references.

Upvotes: 1

NargiT
NargiT

Reputation: 61

Up until you do no call new no memory allocation is done.

So TrieNode[] arr; act as a future reference. Only when you call the constructor, Java will allocate the memory and set the reference inside arr.

Links:

Upvotes: 0

Related Questions