title: Comparing two objects, either of which could be null
body: <p>I have a function in one of my classes that compares itself with another instance of the same class - and finds out which variables differ. This is for the purpose of minimizing network load with a main database (by only uploading data that needs to be uploaded, instead of uploading the whole object).</p>
  
  <p>For this, I have been trying to make use of the <code>object.equals()</code> function to compare the two objects.</p>
  
  <p>I soon found that the <code>object.equals()</code> does not handle <code>null</code>s, and after reading <a href="https://stackoverflow.com/questions/2887761/is-it-a-bad-idea-if-equalsnull-throws-nullpointerexception-instead">this question</a>, I understand why.</p>
  
  <p>So an example of my broken code is as follows:</p>
  
  <pre><code>public class MyObject {
  
      String myString;
      String myString2;
  
      public String getChangedVars(MyObject comparisonObj) {
          ArrayList&lt;String&gt; changedVars = new ArrayList&lt;String&gt;();
  
          if (!this.myString.equals(comparisonObj.myString))
              changedVars.add("myString");
          if (!this.myString2.equals(comparisonObj.myString2))
              changedVars.add("myString2");
  
          return changedVars.toString();
      }
  }
  </code></pre>
  
  <p>My question is - on the basis that <em>either</em> one of the variables being compared <em>could</em> be null, what is a simple way to compare two variables whilst avoiding a <code>NullPointerException</code>?</p>
  
  <p>Edit:
  Simply checking for null on both objects first doesn't work well, as I <em>still</em> want to compare if the object has a reference or not. Eg, if one item is <code>null</code> and the other is not, I want this to resolve to <code>true</code>, as the variable <em>has changed</em>.</p>