7

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);
  }
}
0

2 Answers 2

11

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.

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

Comments

0

The static block will only be executed when your class loads. This will be done in the following cases:

  1. Initially when your program starts
  2. If you load your class manually at runtime

    Ex : using Class.forName("Foo"))

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.