Saturday, 1 May 2021

What is Effectively Final in Java 8

     In Java 8, introduced one new concept called "effectively final" variable.

A variable or parameter whose value is never changed after it is initialized is effectively final. 

     There is no need to explicitly declare such a variable as final; however, declaring it as final will not cause any issues. An effectively final variable can be used inside an anonymous class or lambda expression, but its value cannot be changed within them.

Example of effectively final:-

String str = "Acuver Consulting";
List<String> skuList = Arrays.asList("MTCCC", "MTBBB");
		
skuList.stream().forEach(s -> 
	System.out.println(str)
);

In above example, str variable is Effectively Final variable.

Example of non effective final variable,

String str = "Acuver Consulting";
str = str.concat("Pvt Ltd");
List<String> skuList = Arrays.asList("a", "b");
		
skuList.stream().forEach(s -> 
	System.out.println(str)    //Compile Time Error 
);

      When we use non effective final variable inside lambda expression or inside anonymous class, then will throw a Compile Time Error as,
"Local variable str defined in an enclosing scope must be final or effectively final"

       The difference between a final variable and an effectively final variable is that a final variable is explicitly declared using the final keyword and cannot be reassigned after it is initialized. An effectively final variable, on the other hand, is not explicitly declared as final, but its value is never modified after initialization, so the compiler treats it as if it were final.

Lambda expressions can access both final and effectively final local variables. However, if the value of a local variable is modified after it is initialized, it is no longer effectively final and therefore cannot be accessed from within a lambda expression.


Related Posts:-