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, although if you declare final it won't cause any issue. This effectively final variable can be used inside anonymous class or lambda expression and can not change this variable value inside anonymous class or lambda expression.

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"

       Difference between final and effective final variable is final variable we can explicitly declare variable with final keyword and can not reassign variable value but effective final variable no need to declare variable with final keyword and value can not be changed once it's initialized. If we change the value i.e mutable variable can not access inside the lambda expression.


Related Posts:-