Search code examples
javafinal

Java using final keyword inside a method


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.


Solution

  • You can.

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

    Will compile just fine.