Why Should I Use the Keyword "Final" on a Method Parameter in Java

final keyword in method parameters

Java always makes a copy of parameters before sending them to methods. This means the final doesn't mean any difference for the calling code. This only means that inside the method the variables can not be reassigned.

Note that if you have a final object, you can still change the attributes of the object. This is because objects in Java really are pointers to objects. And only the pointer is copied (and will be final in your method), not the actual object.

Why Final is used in method parameters

final is used in method parameters to make the references unchangeable after it is passed into the method. This is a specialized way of securing the passed parameters. so, the method receiving will not be able to re-initialize it with new object or value

What is the purpose having final keyword in method parameter?

final variables means you can not change the value.

For example final int x=9; and after that if you change it with x=6; then it will not compile.

So in your case

public void display(final String toDisplay){

}

In this method you are allowing a String argument and after that within that method if you try to change then it will not compile.

What is the purpose of declaring method parameters final?

Sometimes, it helps the fellow programmers or maintenars that they should not change the value of that variable.

Ex: Imagine a method taking a string parameter. Imagine that it a very long method having 1000 lines of code. If the parameter is not marked as final, the second programmer see an opportunity of changing the value in it. The first programmer resumes the work on the method while not having the knowledge that the variable is assigned a new value.
Making it final will fully assure the first programmers intention to be passed on to second.

Apart from this, if you need to use this variable in any of anonymous class in that method, you can't use it unless it is final.

Hope this helps.

Is there any performance reason to declare method parameters final in Java?

The final keyword does not appear in the class file for local variables and parameters, thus it cannot impact the runtime performance. It's only use is to clarify the coders intent that the variable not be changed (which many consider dubious reason for its usage), and dealing with anonymous inner classes.

There is a lot of argument over whether the final modifier on the method itself has any performance gain since the methods will be inlined by the optimizing compiler at runtime anyway, regardless of the modifier. In this case it should also only be used to restrict the overriding of the method.

When should one use final for method parameters and local variables?

Obsess over:

  • Final fields - Marking fields as final forces them to be set by end of construction, making that field reference immutable. This allows safe publication of fields and can avoid the need for synchronization on later reads. (Note that for an object reference, only the field reference is immutable - things that object reference refers to can still change and that affects the immutability.)
  • Final static fields - Although I use enums now for many of the cases where I used to use static final fields.

Consider but use judiciously:

  • Final classes - Framework/API design is the only case where I consider it.
  • Final methods - Basically same as final classes. If you're using template method patterns like crazy and marking stuff final, you're probably relying too much on inheritance and not enough on delegation.

Ignore unless feeling anal:

  • Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.

  • Edit: note that one use case where final local variables are actually very useful as mentioned by @adam-gent is when value gets assigned to the var in the if/else branches.

Does final keyword on method parameter get compiled to bytecode?

TL;DR: You don’t need that information in the bytecode

The final keyword on a parameter means that you cannot assign a value to that parameter inside your method or constructor. It’s the compiler’s job to check that you are not doing this (and the compiler will issue an error message if you do). Once the compiler has done its job, we can be assured that the parameter indeed keeps its initial value throughout. There is no need to have the information in the bytecode that the parameter is declared final. Which is why the information is not there.

From a comment by Link182:

Then how do we know the parameter is final in a compiled library?

You don’t. You don’t need to. What would you use that information for? It’s only relevant for the implementor of the method.

Making java method arguments as final

As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.

This saves you from declaring another local final variable in the method body:

 void m(final int param) {
new Thread(new Runnable() {
public void run() {
System.err.println(param);
}
}).start();
}

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

You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.



Related Topics



Leave a reply



Submit