android – Why make local variables final in a static method?


One of the standard examples – SampleSyncAdapter – contains this snippet:

public static boolean authenticate(String username, String password, Handler handler, **final Context context**) {
    **final HttpResponse resp;**

    **final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();**
    params.add(new BasicNameValuePair(PARAM_USERNAME, username));
    params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params);
    } catch (**final UnsupportedEncodingException e**) {
        // this should never happen.
        throw new AssertionError(e);
    **final HttpPost post = new HttpPost(AUTH_URI);**

Further, some variables are also marked as final. What for?


It's not a static method, final can be used everywhere. There are 2 reasons for using final :

  1. When the compiler meets the final keyword, it tries to optimize the code, bearing in mind that the value of this variable will not change further. You can win a few pennies (saving the stack or speed) due to such optimization.
  2. In addition, a programmer can deliberately use the word final in order to control at the compilation stage whether its meaning will change or not. That is, if there is an attempt to modify the value assigned during initialization, the compiler will generate an error. Some developers think that this is ice.
  3. This variable will be captured by the anonymous class (Valid for versions less than 8). In order to capture variables in the context, they must be marked as final. Starting from version 8, the compiler itself can determine whether a variable is effectively final and the keyword becomes optional.
Scroll to Top