Search code examples
javadata-structurestrie

Can we not initialize reference array in Trie constructor


In this Trie implementation, children array elements are assigned null value individually using a for loop.

TrieNode(){ 
    isEndOfWord = false; 
    for (int i = 0; i < ALPHABET_SIZE; i++) 
    children[i] = null; 
}

However, by default, when we create an array of reference types in Java, all entries will have default value as null which is:

TrieNode[] children = new TrieNode[ALPHABET_SIZE];

The above step assigns default values of children array entries as null.

Is it required to have null assignment once again in the for loop inside that TrieNode constructor?


Solution

  • No it's not required - for each class variable, instance variable, or array component Java will always assign reasonable default value (like 0 for int or null for Object) - you can read more here

    However notice that for local variables it's not guaranteed

    The compiler will assign a reasonable default value for fields of the above types; for local variables, a default value is never assigned.

    and that's why you are forced to initialize it manually

    public void f() {
        String s;
        System.out.println(s); // will cause Error: java: variable s might not have been initialized
    }