File tree 2 files changed +47
-0
lines changed
Modern-Java-Examples/src/com/learn/lambdas
2 files changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -20,6 +20,7 @@ This repository contains the basic & advance level examples related to Java
20
20
* [ Consumer Method Reference] ( Modern-Java-Examples/src/com/learn/methodreference/ConsumerMethodReferenceExample.java )
21
21
* [ Refactoring Method Reference] ( Modern-Java-Examples/src/com/learn/methodreference/RefactorMethodReferenceExample.java )
22
22
* [ 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 )
23
24
24
25
25
26
You can’t perform that action at this time.
0 commit comments