I am executing below in main method:
int secrete = 42;
for (int i = 0; i < 5; i++) {
Consumer<String> myprinter2 =
msg -> {
System.out.println("consuming " + msg + " ," + secrete);
};
myprinter2.accept(myprinter2.toString());
}
The output for the above code is:
consuming Main$$Lambda$1/1324119927@6d311334 ,42
consuming Main$$Lambda$1/1324119927@682a0b20 ,42
consuming Main$$Lambda$1/1324119927@3d075dc0 ,42
consuming Main$$Lambda$1/1324119927@214c265e ,42
consuming Main$$Lambda$1/1324119927@448139f0 ,42
If I change secrete to be final, then the output is:
consuming Main$$Lambda$1/2003749087@41629346 ,42
consuming Main$$Lambda$1/2003749087@41629346 ,42
consuming Main$$Lambda$1/2003749087@41629346 ,42
consuming Main$$Lambda$1/2003749087@41629346 ,42
consuming Main$$Lambda$1/2003749087@41629346 ,42
secrete is effectively final even if I do not declare it final, so why is each lambda considered a new object when I do not declare it final?