final variable in methods in Java

35,210

Solution 1

It simply makes the local variable books immutable. That means it will always be a reference to that same Book object being created and built, and cannot be changed to refer to another object, or null.

The Book object itself is still mutable as can be seen from the sequence of accessor calls. Only the reference to it is not.

Solution 2

In this case, final Books books simply means that books must be assigned a value exactly once.

I like to use the final keyword like this as it shows intent of the variable, which I find to be valuable information when looking at code as it removes yet another variable from the situation...so to speak.

If I don't mark a variable as final then it stands out as something to keep my eye on because it's going to change values sometime soon. This information is helpful while, for example, stepping through the code in the debugger or refactoring & moving around code.

Solution 3

This likewise makes the variable reference read-only. Usually, this is to protect the code from accidentally modifying a variable that must not change.

Solution 4

I'm pretty sure it means nothing more than the variable books cannot be overwritten later on in the method.

Solution 5

This code is using anonymous class JsonHttpRequestInitializer, where it refers to the local variable in method queryGoogleBooks, the problem in this kind of situation is that the queryGoogleBooks method could return before initialize method of the JsonHttpRequestInitializer is completed, where it could cleanup the variable and could cause the initialize method of JsonHttpRequestInitializer to fail. So it is required to declare the variables as final in this type of situations. For more details refer to,

Cannot refer to a non-final variable inside an inner class defined in a different method

Share:
35,210
Tarik
Author by

Tarik

I am a software engineer with interests in different technologies.

Updated on August 04, 2020

Comments