Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to have a final input parameter in method signature?

What would be the reason for doing the below:

public void processSomething(final String hello, final String two, final Car car){}

as opposed to:

public void processSomething(String hello, String two, Car car){}
like image 213
Oh Chin Boon Avatar asked Jun 28 '11 10:06

Oh Chin Boon


People also ask

Can a methods parameters be final?

The final keyword on a method parameter means absolutely nothing to the caller. It also means absolutely nothing to the running program, since its presence or absence doesn't change the bytecode. It only ensures that the compiler will complain if the parameter variable is reassigned within the method. That's all.

What is meant by signature of a method?

The method signature in java is defined as the structure of the method that is designed by the programmer. The method signature is the combination of the method name and the parameter list. The method signature depicts the behavior of the method i.e types of values of the method, return type of the method, etc.

How do you make a parameter final in Java?

The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment.

Can we pass final variable to method in Java?

You can pass final variables as the parameters to methods in Java. A final variable can be explicitly initialized only once. A reference variable declared final can never be reassigned to refer to a different object. However, the data within the object can be changed.


2 Answers

It means that within the method, you can't assign new values to the parameters.

A common reason for wanting to do this is to be able to use the parameters within anonymous inner classes which can only reference final local variables, including parameters.

Another reason for doing this is if your coding style favours declaring all local variables as final if possible. (Personally I try to treat them as final, but avoid actually declaring them that way, as it adds cruft.)

like image 197
Jon Skeet Avatar answered Oct 12 '22 01:10

Jon Skeet


It means you cannot change the references. String is immutable, but if Car is mutable you can change the fields in that Car, you can't change it to another Car.

like image 31
Peter Lawrey Avatar answered Oct 11 '22 23:10

Peter Lawrey