Java Musings – initializing a final variable with an uninitialized final variable

Java has fewer quirks compared to C++, but sometimes I do come across surprises.
A code like following will fail to compile since you are trying to initialize a variable with an uninitialized variable.

public class Sample {

  private final String mField1;
  private final String mField2 = mField1 + " two";

  private Sample(String field1) {
    mField1 = field1;
  }
}

But if instead of directly referencing mField1, you reference indirectly via a getter method code will compile, and mField2 will get “null” value for mField1.

public class Sample {

  private final String mField1;
  private final String mField2 = getField1() + " two";

  private Sample(String field1) {
    mField1 = field1;
  }

  private String getField1() {
    return mField1;
  }

  private String getField2() {
    return mField2;
  }

  public static void main (String[] args) {
    Sample sample = new Sample("one");
    // prints "Field 1 is one"
    System.out.println("Field 1 is " + sample.getField1());
    // prints "Field 2 is null two"!!!
    System.out.println("Field 2 is " + sample.getField2());
  }
}

One Reply to “Java Musings – initializing a final variable with an uninitialized final variable”

  1. Good catch!

Leave a Reply

Your email address will not be published. Required fields are marked *