1

I have a class as where I am trying to print a final variable before its initialisation and get the compile error as follows (which is a expected result since using default value of final variable is only allowed through a method),

public class Test{
    private final int x;

    Test(){
      System.out.println("Here x is " + x); // Compile time error: variable 'x' might not be initialized
      x = 7;
      System.out.println("Here x is " + x);
      System.out.println("const called");
   }
    public static void main(String[] args) {
      Test test = new Test();
   }
}

But surprisingly printing x using this reference as this.x works as below and print 0,

public class Test{
    private final int x;

    Test(){
      System.out.println("Here x is " + this.x); // Not a Compile time error and prints 0
      x = 7;
      System.out.println("Here x is " + x);
      System.out.println("const called");
   }
    public static void main(String[] args) {
      Test test = new Test();
   }
}

Can anyone explain why the code behaving like this ??

Rajesh Gupta
  • 233
  • 2
  • 5

0 Answers0