How to use a final or effectively final variable in lambda expression in Java?

Java 8Object Oriented ProgrammingProgramming

The effectively final variables refer to local variables that are not declared final explicitly and can't be changed once initialized. A lambda expression can use a local variable in outer scopes only if they are effectively final.


(optional) (Arguments) -> body

In the below example, the "size" variable is not declared as final but it's effective final because we are not modifying the value of the "size" variable.


interface Employee {
   void empData(String empName);
public class LambdaEffectivelyFinalTest {
   public static void main(String[] args) {
      int size = 100;
      Employee emp = name -> {        // lambda expression
               System.out.println("The employee strength is: " + size);
               System.out.println("The employee name is: " + name);


The employee strength is: 100
The employee name is: Adithya
Updated on 10-Jul-2020 11:58:59