hakki
hakki

Reputation: 6519

Why final field variable can not assign to blank in Java?

Like other variables, i want to assign final field type variable to blank but initialization is blocking by Java. What is the its logic? Maybe i want to use default values of my variables? for int = 0, string = null boolean = false etc...

public class Hello {

static final int myNumber; /* it is giving "The blank final field myNumber 
                                may not have been initialized" error in Eclipse */
}

Upvotes: 2

Views: 9516

Answers (5)

VonC
VonC

Reputation: 1326776

Eclipse 2019-09 now proposes a quickfix for that:

Initialize 'final' fields

A Java quickfix is now offered to initialize an uninitialized final field in the class constructor.

https://www.eclipse.org/eclipse/news/4.13/images/finalquickfix1.png

The fix will initialize a String to the empty string, a numeric base type to 0, and for class fields it initializes them using their default constructor if available or null if no default constructor exists.

https://www.eclipse.org/eclipse/news/4.13/images/finalquickfix2.png

Upvotes: 0

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

A final variable can only be initialized once, either via an initializer or an assignment statement. It does not need to be initialized at the point of declaration: this is called a "blank final" variable.

change your code

public class Hello {

final int myNumber; 
 public Hello(int num){
 this.myNumber = num;
}

}

for static final variable use static block for initialization

static{
        myNumber = 0;
    }

Upvotes: 3

Josep
Josep

Reputation: 13071

From the Java specs : "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."

Upvotes: 1

parker.sikand
parker.sikand

Reputation: 1381

In Java, after you use the final keyword with a static variable, you must define the value at the point of declaration. You must give it some value and stick with it.

Upvotes: 4

Cruncher
Cruncher

Reputation: 7812

When you use the "final" modifier with a variable, you must initialize it then as it is the only time you're allowed to use the assignment operator(you can initialize once if you left it blank) on it ("="). Like parker.sikand said, you will get an error if you try to assign a value to it afterwards.

Also, an important note that final STRICTLY means that you cannot use the assignment operator. If the object that is "final" is a mutable object then of course the contents of that object can change without ever using the assignment operator.

EDIT: I believe a final variable has to be guaranteed to be initialized at SOME point in the program which is why you generally initialize it on declaration

Upvotes: 0

Related Questions