title: Java: How to check for null pointers efficiently
body: <p>There are some patterns for checking whether a parameter to a method has been given a <code>null</code> value.</p>
  
  <p>First, the classic one. It is common in self-made code and obvious to understand.</p>
  
  <pre><code>public void method1(String arg) {
    if (arg == null) {
      throw new NullPointerException("arg");
    }
  }
  </code></pre>
  
  <p>Second, you can use an existing framework. That code looks a little nicer because it only occupies a single line. The downside is that it potentially calls another method, which <em>might</em> make the code run a little slower, depending on the compiler.</p>
  
  <pre><code>public void method2(String arg) {
    Assert.notNull(arg, "arg");
  }
  </code></pre>
  
  <p>Third, you can try to call a method without side effects on the object. This may look odd at first, but it has fewer tokens than the above versions.</p>
  
  <pre><code>public void method3(String arg) {
    arg.getClass();
  }
  </code></pre>
  
  <p>I haven't seen the third pattern in wide use, and it feels almost as if I had invented it myself. I like it for its shortness, and because the compiler has a good chance of optimizing it away completely or converting it into a single machine instruction. I also compile my code with line number information, so if a <code>NullPointerException</code> is thrown, I can trace it back to the exact variable, since I have only one such check per line.</p>
  
  <p>Which check do you prefer, and why?</p>