Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is static code always executed when we use a class for the first time?

Our application is using initialization code that depends on the order static code is executed and I'm wondering if this order will be consistent across all JVMs.

Here is a sample of what I mean:


public class Main {

    static String staticVar = "init_value";

    public static void main(String[] args) {

        System.out.println(A.staticVar);
        staticVar = "mainValue";
        System.out.println(A.staticVar);
    }
}

public class A {
    static String staticVar = Main.staticVar;
}

will give:

init_value
init_value

and


public class Main {

    static String staticVar = "init_value";

    public static void main(String[] args) {

        // System.out.println(A.staticVar);
        staticVar = "mainValue";
        System.out.println(A.staticVar);
    }
}

public class A {
    static String staticVar = Main.staticVar;
}

will give (on my environment):

mainValue

To summarize, across all JVMs, is static code always executed when we use a class for the first time?

like image 211
matthieus Avatar asked Jul 07 '10 15:07

matthieus


People also ask

Do static methods run automatically?

It is invoked automatically. The user has no control on when the static constructor is executed in the program. A static constructor is called automatically. It initializes the class before the first instance is created or any static members declared in that class (not its base classes) are referenced.

Does a static method need to be in a static class?

A static method is a method that belongs to a class, but it does not belong to an instance of that class and this method can be called without the instance or object of that class.

Which will execute first static block or static variable?

Answer is to use Static block as they get initialized before main so you can use them to print anything without having any dependency on main Method in java.

Can we use static before a class?

In order to create a static member (block, variable, method, nested class), you need to precede its declaration with the keyword static. When a member of the class is declared as static, it can be accessed before the objects of its class are created, and without any object reference.


2 Answers

EDIT: Despite all the reassurances below, if you're thinking of relying on this sort of thing, I would try hard to refactor your code so that it doesn't crop up. While it is guaranteed to work, it's also likely to make your code very brittle. The fact that static initializers get called "invisibly" makes them relatively hard to reason about and debug.


Yes, this is guaranteed by the language specification. From section 8.7 of the spec:

Any static initializers declared in a class are executed when the class is initialized and, together with any field initializers (§8.3.2) for class variables, may be used to initialize the class variables of the class (§12.4).

StaticInitializer: static Block

It is a compile-time error for a static initializer to be able to complete abruptly (§14.1, §15.6) with a checked exception (§11.2). It is a compile-time error if a static initializer cannot complete normally (§14.21).

The static initializers and class variable initializers are executed in textual order.

And from section 12.4:

Initialization of a class consists of executing its static initializers and the initializers for static fields declared in the class. Initialization of an interface consists of executing the initializers for fields declared in the interface.

Before a class is initialized, its direct superclass must be initialized, but interfaces implemented by the class need not be initialized. Similarly, the superinterfaces of an interface need not be initialized before the interface is initialized.

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable (§4.12.4).
  • T is a top-level class, and an assert statement (§14.10) lexically nested
like image 115
Jon Skeet Avatar answered Nov 14 '22 23:11

Jon Skeet


Static initialisers (e.g. your staticVar declarations) are always executed when you use a class for the first time.

Static methods are only executed when they are called. In your case, this is happening because the static void main(String[] args) is the entry point to your application. But if you defined a different static method then it would not be called.

It is also possible to create a static initialiser block that will also be called automatically before the class is first used, e.g.

static {
  // some initialisation code here
}
like image 27
mikera Avatar answered Nov 14 '22 23:11

mikera