title: Nullpointer exception in Hashmaps
body: <p>I’m trying to add Products to my <code>OrderLine</code> (which is held by an Order) but when I try I get the <code>NullPointerException</code>.</p>
  
  <pre><code>import java.util.*;
  public class OrderLine;
  
  private HashMap&lt;Integer, Integer&gt; products = new HashMap&lt;Integer, Integer&gt;();
  
  //setter and getter for products
  
  public void add(int productNbr, int amount) {
      int newAmount = this.products.get(productNbr) + amount;
      this.products.put(productNbr, newAmount);
  }
  </code></pre>
  
  <p>And my Main-tester;</p>
  
  <pre><code>public class Main {
  
  public static void main(String[] args) {
  
  OrderLine ol = new OrderLine();
  ol.add(1, 661);
  ol.add(1, 5); //key 1 should hold value 666
  System.out.println(ol.getProducts()); //Should print out {1, 666}
  </code></pre>
  
  <p>But all I get is "Exception in thread "main" java.lang.NullPointerException". 
  I get the feeling that it works if I define/initiate the value before I add anything to it, but I shouldn't have to do that every time. Any ideas?</p>
  
  <p><strong>UPDATE: Fixed version;</strong></p>
  
  <pre><code>public void add(int productNbr, int amount) {
      if (this.products.get(productNbr) != null) {
          int newAmount = this.products.get(productNbr) + amount;
          this.products.put(productNbr, newAmount);
      } else {
          this.products.put(productNbr, amount);
      }
  }
  </code></pre>