title: Order of static variable initialization, Java
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/3499214/java-static-class-initialization">Java static class initialization</a><br>
    <a href="https://stackoverflow.com/questions/12448465/in-what-order-are-static-blocks-and-static-variables-in-a-class-executed">in what order are static blocks and static variables in a class executed?</a>  </p>
  </blockquote>
  
  
  
  <p>When I run this code the answer is 1, I thought it would be 2. 
  What is the order of initialization and the value of k in each step?</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Test {
  
      static {k = 2;}
      static int k = 1;
  
      public static void main(String[] args) {
          System.out.println(k);
      }
  }
  </code></pre>
  
  <p>Edit 1: As a follow up to "k is set to default value" then why this next code doesn't compile? Theres an error "Cannot reference a field before it's defined".</p>
  
  <pre class="lang-java prettyprint-override"><code>public class Test {
  
      static {System.out.println(k);}
      static int k=1;
  
      public static void main(String[] args) {
          System.out.println(k);
      }
  }
  </code></pre>
  
  <p>Edit 2: For some unknow to me reason it^ works when instead of "k" its "Test.k".</p>
  
  <p>Thanks for all the answers. this will sufice :D</p>