draganstankovic
draganstankovic

Reputation: 5426

Why would anyone make additional local variable just to put final keyword on it?

I've encountered the code similar to this:

public void foo(String param1) { 
    final String param1F = param1;
    ...
}

I doubt that the author doesn't know that he can put final keyword directly in the method signature cause in the rest of the method he only uses param1F but I'm curious if anyone has the idea for what this could be useful?

Upvotes: 4

Views: 281

Answers (3)

agsamek
agsamek

Reputation: 9054

This is required if you need to access the variable from an anonymous class, eg.:

Runnable f(int i) {
    final int i2 = i;
    return new Runnable() {
        public void run() {
            System.out.println(i2);
        }
    };
}

Upvotes: 2

irreputable
irreputable

Reputation: 45433

maybe it's just me, but I feel weird about writing to method parameters, or declaring them final. I think they should be final by default. they should not be "variable"

Upvotes: 0

Andreas Dolk
Andreas Dolk

Reputation: 114767

In this case, you could reassign param1, which wouldn't be possible, if param1 was final.

So there is a slight difference. But to me it is not useful, just because I do not change method parameters in general.

Upvotes: 0

Related Questions