title: Why are my fields initialized to null or to the default value of zero when I've declared and initialized them in my class' constructor?
body: <p><sub>This is meant to be a canonical question and answer for similar questions where the issue is a result of <em>shadowing</em>.</sub></p>
  
  <hr>
  
  <p>I've defined two fields in my class, one of a reference type and one of a primitive type. In the class' constructor, I try to initialize them to some custom values.</p>
  
  <p>When I later query for those fields' values, they come back with Java's default values for them, <code>null</code> for the reference type and 0 for the primitive type. Why is this happening?</p>
  
  <p>Here's a reproducible example:</p>
  
  <pre><code>public class Sample {
      public static void main(String[] args) throws Exception {
          StringArray array = new StringArray();
          System.out.println(array.getCapacity()); // prints 0
          System.out.println(array.getElements()); // prints null
      }
  }
  
  class StringArray {
      private String[] elements;
      private int capacity;
      public StringArray() {
          int capacity = 10;
          String[] elements;
          elements = new String[capacity];
      }
      public int getCapacity() {
          return capacity;
      }
      public String[] getElements() {
          return elements;
      }
  }
  </code></pre>
  
  <p>I expected <code>getCapacity()</code> to return the value 10 and <code>getElements()</code> to return a properly initialized array instance. </p>