1

I understand the purpose of static keyword but regretfully I can't figure out this simple code. Don't know why? I'm expecting the answer to be really simple.

public class VariableScope {

    int x=y;
    static int y=5;

    public static void main(String[] args) {
        System.out.println(new VariableScope().x); 
    }
}

How x gets printed as 5 when y was assigned to it at an earlier stage?

4
  • 2
    What do you expect it to print? When you do think the static assignment happens? Please enumerate explicitly what you expect to happen? Commented Nov 9, 2014 at 18:15
  • Because all statics are initialised before everything else (in your case, local x) when the programme is launched. Commented Nov 9, 2014 at 18:16
  • @hagubear this is an utterly fallacious over-simplification. Commented Nov 9, 2014 at 18:17
  • This is example 8.3.2.2-1 in the JLS Initializers for Instance Variables The adjacent sections are also good reads: Restrictions on the use of Fields during Initialization and Initializers for Class Variables. Commented Nov 9, 2014 at 18:17

2 Answers 2

9

The static initialization static int y = 5 happens during class loading.

The x = y assignment happens during the instance construction new VariableScope(); so at this point y has the value 5 already.

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

1 Comment

Simple and correct! If only there were more answers like this!
2

It's because order the lines of the code does not matter here. Static member is initialized first, then x is initialized.

Here is detailed specification of the initialization order: Java Language Specification 12.4.2. Detailed Initialization Procedure

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.