0

How does this code work fine and prints 9?

public class Dog{

    static {
        age=9;
    }

    static int age=7;

}

And this code doesn't compile(illegal forward reference)? Notice I changed age in static block.

public class Dog{

    static {
        age++;
    }

    static int age=7;

}

Another question is how do both of them even work? From my prior Java knowledge I knew a rule that:

you can't access variable before declaring them

. So how does static block know what variable age actually is?

1 Answer 1

2
public class Dog{

   static {
      age=9;
   }

   static int age=7;
}

Static blocks and static variable initialisations are executed in the order in which they appear in source file. (java documentation point 9

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

In Above case, you are doing an assignment before declaring a variable which is permitted by java in certain cases. Forward References During Field Initialization

The use is on the left-hand side of an assignment;

public class Dog {
   static {
      age++;
   }
   static int age=7;
}

In this case, you are reading it before declaring it which is not permitted. That's why you are getting an illegal forward reference exception.

j = 200; // ok - assignment
j = j + 1; // error - right hand side reads before declaration

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.