Search code examples
javasyntaxfinal

Is it possible to initialize a final variable after declaring..?


Is this even possible, few argue its possible and i saw it here too link.. but when i personally tried it gives me compile time errors..

i mean this,

Class A{
    private final String data;

    public A(){
        data = "new string";
    }
}

Thanks in advance..


Solution

  • Yes, it is possible. Class is written with small case c. Otherwise your code is perfectly fine (except for identation):

    public class A {
       private final String data;
    
       public A() {
          data = "new string";
       }
    }