Search code examples
javafinal

final variable in methods in Java


Possible Duplicate:
Why would one mark local variables and method parameters as “final” in Java?

I was checking some Java code, I am not good at java at least have some knowledge what final does such as sealed classes, readonly fields and non-overridable methods but this looks weird to me, declaring a variable final in methods:

private static void queryGoogleBooks(JsonFactory jsonFactory, String query) throws Exception {
    // Set up Books client.
    final Books books = Books.builder(new NetHttpTransport(), jsonFactory)
        .setApplicationName("Google-BooksSample/1.0")
        .setJsonHttpRequestInitializer(new JsonHttpRequestInitializer() {
          @Override
          public void initialize(JsonHttpRequest request) {
            BooksRequest booksRequest = (BooksRequest) request;
            booksRequest.setKey(ClientCredentials.KEY);
          }
        })
        .build();

Could you tell me what the meaning of final is in this context?

Here is the complete code:

http://code.google.com/p/google-api-java-client/source/browse/books-cmdline-sample/src/main/java/com/google/api/services/samples/books/cmdline/BooksSample.java?repo=samples


Solution

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