For example in the case of an anonymous inner class, an (anonymous) object reference is passed and methods of that object are executed.
Lambdas are code blocks which will be executed when needed.
What happens in the JVM when lambdas are encountered? Where does the JVM store the code blocks related to lambdas (Heap : Young, Old or Permanent Generation)?
I tried searching, and I got the syntax for using lambdas but was not able to understand what is happening inside JVM, as in JAVA everything is object-based.
So in context of OOP how do lambdas work?
Do lambdas violate OOP concepts?
Is Lambda good for the garbage collector as no objects are created hence no worry about memory issues and clearing memory?
Lambda expressions don't get translated into
anonymous inner classes
, they use invoke dynamic that was introduced in Java 7 to execute functional methods. Check this out.Do they violate
OOP
? I don't think that you should care. Lambdas make your code less verbose, easier to understand, and "easier" to parallelise. And thats what you should care about.From Brain Goetz comment:
invokedynamic
bytecode.See more details from the specification lead of Lambda Expressions JSR.
I wouldn't waste my time thinking whether the lambda expressions are a violation of OO principles. Its goal is to increase the power of a language and not to write an OO code, I don't see how lambdas can violate encapsulation, inheritance or polymorphism.
This article explains how Java handles lambda expressions:
Considering the following code:
The Lambda code