Question

I like to know why Variables that are local to a method cannot be declared final. Is there any specific reason?

Does it mean are there no local constants in Java?

Was it helpful?

Solution

They can be declared final. Your actual problem lies somewhere else.

OTHER TIPS

From the Java specification §4.5.4:

A variable can be declared final. A final variable may only be assigned to once. It is a compile time error if a final variable is assigned to unless it is definitely unassigned (§16) immediately prior to the assignment.

In other words, it is perfectly legal. Moreover, it is considered a best practice to use final with local variables as much as possible.

Consistently using final with local variables (when appropriate) can be useful as well. [...] A reasonable approach is to use final for local variables only if there is at least one non-final local variable in the method; this serves to quickly distinguish the non-final local variables from the others.

who said we cannot. we can declare. You might have confused with static which cannot be used in methods.

Silly mistake! Probably you missed mentioning the reference variable and eclipse complains like 'Syntax error on token "final", invalid Type'. Example final Pojo = new Pojo(); which has missing reference variable while it perfectly works if final Pojo pojo = new Pojo(); I am sure when you asked question here at SO by that time you didn't realize that silly mistake there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top