title: Java avoiding null pointer exception in generic class
body: <p>Okay here are my two classes.My aim is to insert in OBT using generic class.In this case I am trying with Strings.When I call the insert method in the main I keep getting: </p>
  
  <pre><code>Exception in thread "main" java.lang.NullPointerException
  at OBTComparable.insert(OBTComparable.java:37)
  at FindTest.main(FindTest.java:12)
  </code></pre>
  
  <p>I found the problem: Since the var "data" is null , I can't use it to compare.</p>
  
  <p>THE QUESTION:
  How can i change the "data" to avoid the null pointer exception(It will be a String).</p>
  
  <p>Generic OBTComparable class:</p>
  
  <pre><code>public class OBTComparable&lt;Type extends Comparable&lt;Type&gt;&gt;                         
  {
    private boolean empty;
  
    private Type data;
    private OBTComparable left;
    private OBTComparable right;
  
    public OBTComparable()
    {
      setEmpty();
    }
  
    private void setEmpty()
    {
      empty = true;
      data = null;  /////////////////// THE PROBLEM //
      left = null;
      right = null;
    } 
  
    private void setData(Type reqData)
    {
      if (empty)
      {
        empty = false;
        left = new OBTComparable();
        right = new OBTComparable();
      }
      data = reqData;
    }
  
  
    public void insert(Type insertData)
    {
      int compare = data.compareTo(insertData); /////////////// HERE ALSO
      if (empty)
        setData(insertData);
      else if (compare &lt; 0)
        left.insert(insertData);
      else
        right.insert(insertData);
    } 
  
  
    public boolean find(Type findData)
    {
      int compare = findData.compareTo(data);
      if (empty)
        return false;
      else if (compare == 0)
        return true;
      else if (compare &lt; 0)
        return left.find(findData);
      else
        return right.find(findData);
    }    
  
    public int compareTo(OBTComparable&lt;Type&gt; other)
         { return 0; }
  
  } // class
  </code></pre>
  
  <p>Test class:</p>
  
  <pre><code>public class Test
  {
    public static void main(String[] args)
    {
      OBTComparable&lt;String&gt; obt = new OBTComparable&lt;String&gt;();
      String [] insertStrings =
         new String [] { "My", "name", "is", "Mark", "Smith", "and", "my",
                        "hobbies", "include", "films", "music", "computing" };
  
  
      for (int i = 0; i &lt; insertStrings.length; i++)
      {
        obt.insert(insertStrings[i]); //////////// HERE ALSO
        System.out.println("Inserting" + insertStrings[i]);
      }
  
   } // main
  } // class 
  </code></pre>