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 and an effectively final variable is that a final variable is explicitly declared with the final keyword and cannot be reassigned, whereas an effectively final variable does not need to be declared as final, but its value cannot be changed once it is initialized. If the value is changed (i.e., the variable is not effectively final), it cannot be accessed inside a lambda expression.


Related Posts:-