title: NullPointerException error when trying to find last item's value in a linked list
body: <p>I'm still a beginner in Java - I'm trying to create a method that finds the value of the last item in a linked list, and it's throwing a <code>java.lang.NullPointerException</code> error, and it indicates the error is on line 21. From my understanding, a null pointer exception happens when the programmer is calling a reference-type variable to reference basically nothing, since the variable hasn't been declared yet.</p>
  
  <p>For example, if I write <code>Integer k;</code>, I cannot call on <code>k</code> until I declare: <code>k = new Integer(10);</code>. If I write <code>int k;</code>, Java automatically sets the value to 0, since it's a primitive type, and I will be able to call it directly.</p>
  
  <p>In this case, I kind of understand why it's throwing this error, since as you can see in the second line of the <code>getLast()</code> method, I called next, which should be <code>null</code>, since it hasn't been declared yet. However, it's indicating that the error is on line 21, where I reassign <code>last</code>. Why?</p>
  
  <p>How do I fix this code? FYI this is just a practice problem through my school's website, and the task was to complete the <code>getLast()</code> method.</p>
  
  <pre><code>/*
   * Class for representing a linked list of ints.
   */
  public class List {
      public int value;
      public List next;
  
      public List(final int setValue) {
          value = setValue;
      }
  
      /**
       * Return the value of the last item in the list.
       */
      public int getLast() {
          List current = next;
          int last = next.value;
          while(next != null) {
              current = next;
              next = current.next;
              last = next.value;       //ERROR
          }
          return last;
      }
  }
  </code></pre>