Making java method arguments as final

John picture John · Nov 12, 2010 · Viewed 55.5k times · Source

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

Answer

PeterMmm picture PeterMmm · Nov 12, 2010

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();
    }