Junior — Middle
How are anonymous functions like lambdas executed in Java?
sobes.tech AI
Answer from AI
In Java, anonymous functions of the lambda type appeared in version 8 and represent a compact way to implement functional interfaces — interfaces with a single abstract method. When executing a lambda expression, the compiler creates an object that implements this interface and calls its method.
Example:
Runnable r = () -> System.out.println("Hello from lambda");
r.run();
Here, () -> System.out.println(...) is a lambda expression that executes the body of the function when run() is called. Internally, the JVM uses the invokedynamic mechanism for efficient creation and invocation of such functions.