Search code examples
javamethodsargumentsfinal

Making java method arguments as final


What difference that final makes between the code below. Is there any advantage in declaring the arguments as final.

public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){  
    return ....
}

public String changeTimezone(final Timestamp stamp, final Timezone fTz, 
        final Timezone toTz){
    return ....
}

Solution

  • As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.

    This saves you from declaring another local final variable in the method body:

     void m(final int param) {
            new Thread(new Runnable() {
                public void run() {
                    System.err.println(param);
                }
            }).start();
        }