Home > Java > Variable which is “effectively final” in Java 8

Variable which is “effectively final” in Java 8

October 11th, 2017

Java 8 has an interesting feature that I learnt recently.
A variable can become “effectively final”.
Very useful.
For instance, the following class would not compile in Java 1.7.
It would return the following error :
“Cannot refer to the non-final local variable myVocabulary defined in an enclosing scope”.
It would require to add the modifier FINAL to the myVocabulary variable.
In Java 8, there is no need to make it final but make sure you do not change the value once assigned.

package com.celinio.training.threads;

import java.util.Hashtable;

public class MainApplication {
	public static void main(String[] args) {
         // No need to declare this variable FINAL
		Hashtable<String, Integer> myVocabulary = new Hashtable<String, Integer>();

		Thread t = new Thread() {
			public void run() {
				try {
					Thread.sleep(2000);
					myVocabulary.put("Hello", 1);
					myVocabulary.put("Bye", 2);
                   // Compilation error in Java 8
                   // myVocabulary = new Hashtable<String, Integer>();
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		};
		t.start();
	}
}

Assigning a new value to the myVocabulary variable (line 28) would produce an error at compilation time :
“Local variable myVocabulary defined in an enclosing scope must be final or effectively final”

Categories: Java Tags:
Comments are closed.