1 Reply Latest reply on Oct 7, 2016 9:59 AM by Tom with Wiley

    OCA Java 8 Study Guide, Order of Initialization




      I'm going through the Java 8 OCA Study Guide (for 1Z0-808) and I noticed something unexpected while trying out some code.
      On page 202 (Chapter 4->Creating Constructors->Order of Initialization), the order says that after the superclass init the next is "Static variable declarations and static initializers in the order they appear in the file". While trying out some examples I had the following case:

      public class CreatingConstructors {
        static {
          status = "second";
        private static String status = "first";
        public static void main(String[] args) {


      This example compiled and the result was "first". If we just take the order you defined in the book, this behavior is unexpected for two reasons. One, I would expect the compiler to fail because on line 3 I still haven't declared the 'status' variable and even if I thought everything would run fine I would've expected to get "second" as the result becausek, after I found out this compiles, I expected the whole line 5 to be processed before going to the static block.


      To me it seems as though the order of initialization is:
      ...2. Go through static variables' declarations;

      3. Go through static variables' definitions and static initialization blocks in the order they appear in;

      ... (respectively the same for instance initialization before invoking the constructor)


      Am I doing something wrong? Have I misunderstood or missed something in the order of initialization


      Thanks for any help you can provide,