Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why code in static block does not execute?

Tags:

java

When I print the constant in main, the static block does not execute, but when I print stat, it does execute. Is there any importance to static final in Java?

package com.test.doubt;

class Doubt {

  public static final int constant = 123;
  public static int stat = 123;

  static {
    System.out.println("Static Block");
  }
}

public class MyProgram {

  public static void main(String[] args) {
    System.out.println(Doubt.constant);
  }
}
like image 870
januprasad Avatar asked Aug 08 '12 11:08

januprasad


2 Answers

Your code isn't initializing the Doubt class, precisely because Doubt.constant is a constant. Its value is baked into MyProgram at compile-time - you could even delete Doubt.class after compilation and your program would still run.

Run

javap -c com.test.doubt.MyProgram

to have a look at exactly what your code looks like after compilation.

See section 15.28 of the JLS for what constitutes a constant expression. For example, this would still be a constant:

public static final String FOO = "Foo";

and so would all of these:

public static final String FOO = "Foo";
public static final String BAR = "Bar";
public static final String FOOBAR = FOO + BAR;

... but this wouldn't be

public static final String NOT_A_CONSTANT = "Foo".substring(0, 1);
like image 179
Jon Skeet Avatar answered Nov 17 '22 16:11

Jon Skeet


The static final int will get compiled directly into your code as its value. That is to say, the JVM sees and is executing:

System.out.println(123);

and you're not touching your aptly-named Doubt class at all (this is an argument for not specifying constants in this fashion, btw. If you change that value you have to recompile every referencing class)

like image 35
Brian Agnew Avatar answered Nov 17 '22 15:11

Brian Agnew