Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Block Unprocessed in java

Tags:

java

While accessing final static variable with class name why static block is not being processed in java?

class Foo {
  public static final int BAR;
  static {
    System.out.println("Hello");
    }
  }
class Baz {
  public static void quux() {
    System.out.println(Foo.BAR);
  }
}
like image 965
user2253251 Avatar asked Apr 06 '13 21:04

user2253251


People also ask

What is the static block in Java?

In a Java class, a static block is a set of instructions that is run only once when a class is loaded into memory. A static block is also called a static initialization block. This is because it is an option for initializing or setting up the class at run-time.

Can we have static block in Java?

Unlike C++, Java supports a special block, called a static block (also called static clause) that can be used for static initialization of a class. This code inside the static block is executed only once: the first time the class is loaded into memory.

How is static block executed in Java?

Static block code executes only once during the class loading. The static blocks always execute first before the main() method in Java because the compiler stores them in memory at the time of class loading and before the object creation.

How many times static block is executed in Java?

Therefore, only one time static block will be executed. Note: Instance block and constructor both are executed during the object creation but instance block will execute first before the execution of the constructor during the object creation.


1 Answers

It will sometimes - it depends on whether the variable is actually a constant:

  • It has to be either a string or a primitive variable (possibly any other class with a null value; I'd have to check)
  • The initialization expression has to be a constant expression

If that's the case, any references to the variable are effectively turned into the value. So in this code:

class Foo {
    public static final int BAR = 5;
}

class Baz {
    public static void quux() {
        System.out.println(Foo.BAR);
    }
}

The method in Baz is compiled into the same code as:

public static void quux() {
    System.out.println(5);
}

There's no hint of Foo.BAR left in the bytecode, therefore Foo doesn't need to be initialized when the method executes.

If you want to prevent that from happening, you always just make it not be initialized with a constant expression in a variable initializer. For example:

class Foo {
    public static final int BAR;

    static {
        BAR = 5;
    }
}

class Baz {
    public static void quux() {
        System.out.println(Foo.BAR);
    }
}

That would be enough to make Foo.BAR not count as a constant as far as the compiler is concerned.

like image 50
Jon Skeet Avatar answered Sep 22 '22 18:09

Jon Skeet