1

I trying to understand the difference between the two lines below. Why is it returning a zero when I add static to the field.

private static final int this_year = Calendar.getInstance().get(Calendar.YEAR);

From this I get: this_year = 0;

private final int this_year = Calendar.getInstance().get(Calendar.YEAR);

And from this I get: this_year = 2013;

Someone who can explain why the first returns a zero?

Here's the code I use it in:

public class TheKing {
  public static final TheKing theKing = new TheKing();
  private final int beltSize;
  private static final int this_year = Calendar.getInstance().get(Calendar.YEAR);

  private TheKing() { 
    beltSize = this_year - 1930;
  }

  public int beltSize() {
    return beltSize;
  }

  public static void main(String[] args) {
    System.out.println("TheKing wears a size " + 
      theKing.beltSize() + " belt.");
  }
}
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138

2 Answers2

3

When fields are declared static, they are initialized in the static initialization method, meaning that your code looks like the following when compiled:

static {
    theKing = new TheKing();
    this_year = Calendar.getInstance().get(Calendar.YEAR);
}

Notice that the constructor is called before this_year is initialized, and before an int is initialized, it has its default value of 0. In other words, this_year is used before it is set to 2013.

One way to fix this is to simply reverse the order of the declarations:

private static final int this_year = Calendar.getInstance().get(Calendar.YEAR);
public static final TheKing theKing = new TheKing();
FThompson
  • 28,352
  • 13
  • 60
  • 93
1

Static methods are initialized in the order they are given in code.

public static final TheKing theKing = new TheKing();
private static final int this_year = Calendar.getInstance().get(Calendar.YEAR);

So the above would initialize theKing first, which calls the constructor, which uses the uninitialized value of 0 of this_year. If you were to change it to:

private static final int this_year = Calendar.getInstance().get(Calendar.YEAR);
public static final TheKing theKing = new TheKing();

it would work fine.

Or if you remove the static, this_year would get initialized as the object theKing is created.

Community
  • 1
  • 1
Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138