Yes. This is called variable capture. Instance and static variables may be used and changed without restriction in the body of a lambda. The use of local variables, however, is more restricted: capture of local variables is not allowed unless they are effectively final, a concept introduced in Java 8. Informally, a local variable is effectively final if its initial value is never changed (including within the body of a lambda expression)—in other words, declaring it final would not cause a compilation failure. The concept of effective finality does not introduce any new semantics to Java; it is simply a slightly less verbose way of defining final variables. The rationale for requiring captured local variables to be effectively final is explained here.
Leave a Reply