Arka Banerjee
Arka Banerjee

Reputation: 47

I want to initialize a final variable into a function

Program code:

public class A{
   public static final String l;

   public void method(String strTestData){
     l = strTestData;
   }
}

strTestData will contain data like "public static final java.lang.String DELETE". is it possible?

Upvotes: 1

Views: 214

Answers (4)

Vishal K
Vishal K

Reputation: 13066

I want to initialize a final variable into a function

NO,You can't do this. This is in accordance with JLS8.3.12:

It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

A blank final instance variable must be definitely assigned (§16.9) at the end of every constructor (§8.8) of the class in which it is declared; otherwise a compile-time error occurs.

Hence your code would look like this:

public class A{
   public static final String l;
   static
    {
       l = "Static String initialized..";
    }
}

Or, You can initialize final variable at the time of declaration as follows:

public static final String l = "Static String initialized..";

Upvotes: 2

Duncan Jones
Duncan Jones

Reputation: 69339

This is not possible.

If you declare a static final field, it must be initialized in a static inializer or at the point of declaration. You cannot later modify the value. For example:

public static final String l = "Foo";

or

public static final String l;

static {
  l = "Bar";
}

Perhaps you should just remove the final modifier?

Upvotes: 9

Uwe Plonus
Uwe Plonus

Reputation: 9954

You cannot initialize a final variable from a method. This is needed because the compiler needs to ensure that the variable is initialized only once.

A method can be called at any time and therefore the compiler cannot ensure that the variable is only initialized once.

Upvotes: 1

Madsen
Madsen

Reputation: 406

If a variable is declared final, you can only initialize it once. In fact you need to initialize EXACTLY once. This has to happen either when you declare the member variable or in the constructor.

Trying to change it is also impossible.

Upvotes: 1

Related Questions