giri
giri

Reputation: 27199

Why can't variables local to a method be declared final?

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?

Upvotes: 0

Views: 1017

Answers (4)

Sankalp
Sankalp

Reputation: 2086

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.

Upvotes: 0

GuruKulki
GuruKulki

Reputation: 26418

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

Upvotes: 1

jason
jason

Reputation: 241631

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.

Upvotes: 5

BalusC
BalusC

Reputation: 1108702

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

Upvotes: 8

Related Questions