Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

syntax

final

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..

like image 206
ngesh Avatar asked Feb 25 '12 09:02

ngesh


People also ask

Can final variable be initialized after declaration?

Once you declare a variable final, after initializing it, you cannot modify its value further. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them. If not a compile time error will be generated.

Can we assign value to final variable after declaration?

In Java, non-static final variables can be assigned a value either in constructor or with the declaration. But, static final variables cannot be assigned value in constructor; they must be assigned a value with their declaration.

Can we initialize final variable in main method?

A final variable can be initialized only once. A final variable at class level must be initialized before the end of the constructor.

What happens when we declare a variable as final?

A variable cannot be modified after it is declared as final. In other words, a final variable is constant. So, a final variable must be initialized and an error occurs if there is any attempt to change the value.


1 Answers

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";
   }
}
like image 143
Boris Strandjev Avatar answered Sep 23 '22 18:09

Boris Strandjev