IUnknown
IUnknown

Reputation: 9839

final in java method arguments

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?

Upvotes: 3

Views: 222

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136122

This is correct, final helps detect parameter assigment at compile time. However I think it is better to configure compiler to detect this kind of problems. Eg Eclipse has Parameter Assigment setting in Java Compiler Errors/Warnings Preferences.

Upvotes: 0

Mark Peters
Mark Peters

Reputation: 81154

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

Upvotes: 2

Isaac
Isaac

Reputation: 16736

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).

Upvotes: 3

Related Questions