Alex Rivera | Logout

Why would one mark local variables and method parameters as "final" in Java?

Asked 2008-11-25T04:16:23.233
57

In Java, you can qualify local variables and method parameters with the final keyword.

public static void foo(final int x) {
  final String qwerty = "bar"; 
}

Doing so results in not being able to reassign x and qwerty in the body of the method.

This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?

Edit
Report

1 Answer

2

Although it creates a little clutter, it is worth putting final. Ides e.g eclipse can automatically put the final if you configure it to do so.

answered 2010-10-03T23:59:54.753

Your Answer