4

Example 1:

class Temp {
    final int x = getX();

    Temp() {
        System.out.println("Via Constructor : " + this.x);
    }

    int getX() {
        System.out.println("Via get method : " + this.x);
        return 101;
    }

    public static void main(String[] args) {
        new Temp();
    }
}

Output:

via get method : 0
Via Constructor : 101

Not clear the first line of output, As final variable can not be reinitialized, It should not show the default value, Please explain, I spent many hours but could not get the satisfied answer.

Example 2:

class Temp {
    final int x;

    Temp() {
        System.out.println("Constructor one : " + this.x);
        this.x = 10;
        System.out.println("Constructor two : " + this.x);
    }

    public static void main(String[] args) {
        new Temp();
    }
}

Output:

Temp.java:5: error: variable x might not have been initialized    
System.out.println("Constructor one : " + this.x);

Please compare the both example, I am satisfied with the Example 2, but Example 1 is not clear to me. Please help it would be appreciated.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
Kim
  • 305
  • 1
  • 3
  • 14
  • 1
    There **has** to be a good dupetarget for this... – T.J. Crowder Feb 22 '20 at 16:03
  • Hint, when does assignment happen? – Boris the Spider Feb 22 '20 at 16:04
  • in Example 1: it is runtime initialization. and in Example 2: it is before unloading constructor. – Kim Feb 22 '20 at 16:07
  • There is no such thing is "unloading" a constructor. What output do you expect in the first instance? – Boris the Spider Feb 22 '20 at 16:09
  • 1
    Take a look at this question (looks like the same question): https://stackoverflow.com/questions/24990691/will-java-final-variables-have-default-values – Willem Feb 22 '20 at 16:12
  • Hi Boris, sorry edited before completion of constructor call, edited sorry – Kim Feb 22 '20 at 16:13
  • Java Language Specification: [17.5.2. Reading final Fields During Construction](https://docs.oracle.com/javase/specs/jls/se13/html/jls-17.html#jls-17.5.2): "...If the read occurs after the field is set in the constructor, it sees the value the final field is assigned, otherwise it sees the default value." (IMO having default value is not initialization) – user85421 Feb 22 '20 at 17:50

0 Answers0