1

recently,I found that in some projects they really like to add final keyword in the method parameters like:

public static String getSuffix(final String fileName) {
    if (fileName.indexOf('.') >= 0) {
        return fileName.substring(fileName.lastIndexOf('.'));
    }
    return EMTPY_STRING;
}
public HttpResult(final int statusCode) {
    this.statusCode = statusCode;
}
side
  • 209
  • 2
  • 9
  • To enforce the **coding policy** of not allowed changes to a parameter. You don't have to specify `final`, e.g. Eclipse will warn you if you update a parameter (calling it a "Code Style"). – Andreas Aug 31 '15 at 02:46
  • it's a fashion statement. – ZhongYu Aug 31 '15 at 02:49
  • This has already been answered here: http://stackoverflow.com/questions/500508/why-should-i-use-the-keyword-final-on-a-method-parameter-in-java – Zarwan Aug 31 '15 at 03:13

3 Answers3

3

It can help you catch bugs.

For example, if you write :

public HttpResult(final int statusCode) {
    statusCode = statusCode;
}

you will get a compilation error, since you are assigning a value to your local final variable, while if you write

public HttpResult(int statusCode) {
    statusCode = statusCode;
}

you won't get a compilation error, but the statusCode member won't be assigned.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 1
    Of course, a good IDE will tell you "The assignment to variable statusCode has no effect" (Eclipse), so the `final` is not needed for that. – Andreas Aug 31 '15 at 02:47
  • A good IDE will also tell you "The parameter statusCode should not be assigned", eliminating the need for `final`, assuming you enable and listen to the warnings generated by Eclipse. – Andreas Aug 31 '15 at 02:52
0

It's just a cleaner style when you don't want a variable to be altered in any way, even if it isn't necessary.

mcjcloud
  • 351
  • 2
  • 11
0

Java supports Pass by value. So it will always keep a copy of that variable. Hence final key word will not be helpful and will not make any sense in code which is invoking the method.

But inside the method in which that parameter is passed, final keyword will be pretty much helpful. if its final no one can reassign that value.

Rahman
  • 3,755
  • 3
  • 26
  • 43