While going through the lambda expressions, I came across the below behavior for anonymous inner classes and lambda expressions. What could be the reason behind this?
Human h = new Human() {
int a = 2;
@Override
public void sing() {
System.out.println(++a);
}
};
h.sing();
h.sing();
O/P
3
4
Whereas for lambdas I get below:
Human h = () -> {
int a = 2;
System.out.println(++a);
};
h.sing();
h.sing();
}
O/P
3
3
Those are not equivalent. The first function modifies a variable outside of it's scope, whereas in the second example each time you're invoking h.sing();
, the body of that function is being invoked. That means, a
variable is instantiated with value 2 every time.