2

I only spend five minutes to find a duplicate in SO.

My question is simple. Does the following code always work?

public class LexicalOrderStatic {
    private static Integer a1 = initA1();

    private static Integer a2 = initA2();


    private static Integer initA2(){
        return new Integer(5) / a1;
    }

    private static Integer initA1(){
        return new Integer(5);
    }

    public Integer getA1(){
        return new Integer(a2);
    }

    public static void main(String[] args) {
        LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
        System.out.println(lexLuthor.getA1());

    }
}

In java can I be sure that a1 is always initialized before a2 ?

Thanks. Dw is ok if it is asked or if it is very simple.

2 Answers 2

8

In java can I be sure that a1 is always initialized before a2 ?

Yes, because the specification (section 12.4.2) guarantees it (emphasis mine):

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.

Note that constants are initialized earlier than non-constants (step 6 compared with step 9 quoted above).

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

3 Comments

Proud of being answered by you sir :)
What does textual order mean exactly?
@Bato-BairTsyrenov: The order in which they appear in the source code. The declaration for a1 appears before the declaration for a2 in the source code, so it is initialized first.
0

Yes. The chain of elements group ( name of the class, static attributes, instance attributes, static method, inner static block of code, etc) (1) is defined in compile time, not in run time: it has a deterministic behaviour.

When you run main, you have loaded at the first time LexicalOrderStatic and the static elements (attributes, methods) are loaded very quickly if this is the first loading.

If you load a second obejct of LexicalOrderStatic, the attribute are shared between the two instance.

Yu can see this statement in running this modified main

public static void main(String[] args) {
    LexicalOrderStatic lexLuthor = new LexicalOrderStatic();
    System.out.println(lexLuthor.getA1());
    LexicalOrderStatic lexLuthor2 = new LexicalOrderStatic();
    System.out.println(lexLuthor2.getA1());
}

(1) before I referred to inheritance, but it'snt the situation, as pointed by the first comment

1 Comment

It's not clear what exactly you mean by "chain of inheritance" here, or why it's relevant - there's no inheritance being used in this example.

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.