-2

I have written a condition in code where if the value of Object is null, it should initialize a new object, but I am getting null pointer exception at the comparison statement itself. as per my knowlwdge we van compare two null values.

Not sure what a I missing. Below is my code

public class TrieNode
{   
static final int Alphabet_Size = 26;

class Tried
{
Tried children[] = new Tried[Alphabet_Size];
boolean isEndofWord;

   Tried()
   {
     isEndofWord = false;
     /*for(int i=0; i<Alphabet_Size; i++)          
        children[i] = null; */         
   }
};

static Tried root;

   public void insert(String key)
 {
  Tried note = root;
  int index;
  int itr;
 
 for(itr=0; itr<key.length(); itr++)
 {
  
     index = key.charAt(itr)-'a';   
     
        if(note.children[index]==null)       // Getting Null pointer Exception here
        {
            note.children[index] = new Tried();
        }
    
    note = note.children[index];
  }

 note.isEndofWord = true;
}

  
   public boolean search(String key)   
 {
  Tried note = root;
  int index;
  int itr;
 
 for(itr=0; itr<key.length(); itr++)
 {
  index = key.charAt(itr)-'a';
    if(note.children[index]==null)
       return false;
    
    note = note.children[index];   
  }
  
   return (note!=null && note.isEndofWord);
}


public static void main(String[] args)
{
  TrieNode tr = new TrieNode();
  String keys[] = {"the", "their", "Aakash", "Aayush"};

  for(int i=0; i<keys.length; i++)
   {
    tr.insert(keys[i]);
   }

 }

}

I Have tried adding null values for all the indexes in array(see the commented part of code) but even that is not helping

Aakash Goyal
  • 305
  • 1
  • 4
  • 22
  • You are getting a NPE because you are trying to access the `children` member of the `note` variable. `note` is assigned to point to `root`. Based on your program, `root` is never assigned a value, meaning that it is `null` at the time `note` is assigned to it. – ajc2000 Aug 08 '20 at 20:39
  • The note variable itself must be null – DontKnowMuchBut Getting Better Aug 08 '20 at 20:39

1 Answers1

-1

if note itself is null you cannot perform note.children[index] try something like if(note==null) then initialize object

Lokesh
  • 29
  • 1
  • 5