2

In Java, the keyword final is used to indicate that the variable cannot be reassigned. If that is the case, why can't a variable declared inside a method have the final keyword? Why is this not legal:

public void method()
{ 
  final String x = "name";
}

It could come in handy for long methods.

2
  • 5
    Uhm, you can do that... what's the question? Commented May 1, 2012 at 2:07
  • 3
    This is a great example of why you should actually try things before asking questions. Commented May 1, 2012 at 2:46

1 Answer 1

3

You can.

public void foo() {
    final String bar = "bar";
}

Will compile just fine.

Sign up to request clarification or add additional context in comments.

2 Comments

...and behave just as expected. bar = "foo"; on a following line will fail to compile. (final local variables are also accessible in any anonymous inner classes defined in said local scope, which can be handy.)
Thank you. My mistake to assume otherwise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.