Member-only story
Effective final in java lambda
Problem statement : What is Effective final in Java?
You must have faced a scenario where you want to use any variable that has been declared outside of your anonymous class and you had to make the variable as final, as shown below:
// As you can see there is a final keyword added to the field "name"
final String name = Thread.currentThread().getName();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello from "+name);
}
});However, This restriction is removed in java 8. Now it is possible to refer that variables that are not final, but they still have to be effective final.
Being effectively final is that you can assign value to the variable only once.
So whether to use ‘final’ keyword or effective final i.e without declaring ‘final’ keyword its your personal choice.
String name = "hello"; // effective final variable
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello from "+name);
}
});
//lambda expression example
String name = "hello"; // effective final variable
Thread t1 = new Thread(()-> System.out.println("hello from "+name));So you have not declared any variable as final but you can not use them as not final if they are used in Anonymous classes or lambda expression







