Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

final in java method arguments

Tags:

java

final

I needed to confirm if my understanding is correct around final method arguments. If we leave aside anonymous classes from this discussion,the ONLY reason why I would tag a method argument as final is catch something at compile time,rather than scratching my head over a run-time bug later on. Do I get it correct? Or is there some design paradigm I am missing out?

like image 551
IUnknown Avatar asked May 18 '26 09:05

IUnknown


2 Answers

It is considered a bad practice to assign values to parameters, from within a method's body:

public void myMethod (String parm) {
    parm = "some-value";     // This is very frowned upon
}

Declaring the argument as final ensures that you won't pass compilation if you attempt such practice.

There are no other design factors that I am aware of (that is, other than what you had mentioned regarding anonymous classes etc).

like image 97
Isaac Avatar answered May 19 '26 22:05

Isaac


It doesn't make a difference at runtime. This is provable in the most conclusive way: adding the final modifier doesn't even change the compiled bytecode!

FinalParam.java (before)

class FinalParam {
   public static void main(String[] args) {
      System.out.println(java.util.Arrays.toString(args));
   }
}

$ javac -version
javac 1.7.0_15
$ javac FinalParam.java
$ md5sum FinalParam.class
7ca43ea68179f6191d5bf1de7ba21945
$ rm FinalParam.class

FinalParam.java (after)

class FinalParam {
   public static void main(final String[] args) {
      System.out.println(java.util.Arrays.toString(args));
   }
}

$ javac FinalParam.java
$ md5sum FinalParam.class
7ca43ea68179f6191d5bf1de7ba21945
like image 22
Mark Peters Avatar answered May 20 '26 00:05

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!