Skip to content

Commit dc95c40

Browse files
committed
Lambdas and Local Variable
1 parent 809e27a commit dc95c40

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.learn.lambdas;
2+
3+
import java.util.function.Consumer;
4+
5+
public class LambdaVariable1 {
6+
7+
private static int num = 10;
8+
9+
public static void main(String[] args) {
10+
11+
int i = 10; // local Variable
12+
13+
/**
14+
* we can't use the same variable which is
15+
* already defined in this method scope.
16+
*/
17+
Consumer<Integer> consumer1 = (i1) -> {
18+
System.out.println(i1);
19+
};
20+
21+
22+
int value = 5;
23+
/**
24+
* we are not allowed to modify any local variables
25+
* that is being referenced in lambda scope.
26+
*/
27+
Consumer<Integer> consumer2 = (i1) -> {
28+
//i = 10; ( Not allowed )
29+
System.out.println(i1 + value);
30+
};
31+
32+
// value = 5; even we can't do this. since it is referenced in lambda scope.
33+
34+
35+
/**
36+
* For Instance Variables or Class Variables,
37+
* there is no restriction.
38+
*/
39+
Consumer<Integer> consumer3 = (i1) -> {
40+
num = 5;
41+
System.out.println(i1 + num);
42+
};
43+
44+
num = 2;
45+
}
46+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ This repository contains the basic &amp; advance level examples related to Java
2020
* [Consumer Method Reference](Modern-Java-Examples/src/com/learn/methodreference/ConsumerMethodReferenceExample.java)
2121
* [Refactoring Method Reference](Modern-Java-Examples/src/com/learn/methodreference/RefactorMethodReferenceExample.java)
2222
* [Constructor Reference](Modern-Java-Examples/src/com/learn/constructorreference/ConstructorReferenceExample.java)
23+
* [Lambdas and Local Variables](Modern-Java-Examples/src/com/learn/lambdas/LambdaVariable1.java)
2324

2425

2526

0 commit comments

Comments
 (0)