title: When does java execute class-level field assignments?
body: <p>I would consider myself somewhat beginner/intermediate in programming; Most of the time it seems I know how to code things, but I don't know exactly what java does with it. Sometimes I have a field that is assigned in a constructor:</p>
  <pre><code>public class MyClass {
       public int x;
       
       MyClass() {
         x = 5;
       }
  }
  </code></pre>
  <p>...And as far as I know x gets set to 5 when a new object of MyClass is created. However, sometimes I assign fields outside of any constructor or function:</p>
  <pre><code>public class MyClass {
       public int x = 5;
       public static MyOtherClass y = new MyOtherClass();
   
       public MyClass() {
  
       }
  }
  </code></pre>
  <p>When exactly does java run these assignments? Are they also done when an object of MyClass is created, or before then? If I reference a static variable such as &quot;y&quot;:</p>
  <pre><code>public class MyThirdClass {
       public MyOtherClass z = MyClass.y;
  }
  </code></pre>
  <p>Is &quot;y&quot; assigned when I first reference it, or does Java already have it done before then? In this case &quot;y&quot; can't be assigned after creating a new object of MyClass, because I haven't created any objects for it yet. So are all these field assignments outside of constructors and methods done all at once when the program is run, or instead assigned when they are first referenced/needed? Or some other time? Thank you for any info on this.</p>