Search code examples
javafinal

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?


Solution

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