3

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?

0

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.