views:

167

answers:

3

Hi 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?

+8  A: 

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

BalusC
+5  A: 

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.

Jason
For class/instance, you should use final deliberatly, but for local variables (if not accessed by local/anonymous classes), it's more a matter of taste imho.
Helper Method
+1  A: 

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

GK