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) );
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 );
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.
Thanks for sharing this informative content here. Learn Exception Handling in Java
ReplyDelete