Java - Interview Questions and Answers on Lambda Expressions

Q1. What is a Lambda Expression ? What's its use ?

Ans. Its an anonymous method without any declaration. Lambda Expression are useful to write shorthand Code and hence saves the effort of writing lengthy Code.    It promotes Developer productivity, Better Readable and Reliable code.

Q2. Difference between Predicate, Supplier and Consumer ? 

Ans. Predicate represents an anonymous function that accepts one argument and produces a result.

Supplier represents an anonymous function that accepts no argument and produces a result.

Consumer represents an anonymous function that accepts an argument and produces no result.

Q3. What does the following lambda expression means ?

helloJava8 ( x-> x%2 )

Ans. helloJava8 receives an Integer as argument and then returns the modulus of that Integer.

Q4.  Difference between final and effectively final ? Why is effectively final even required ?

Ans. Final variable means a variable that has been declared final and hence cannot be changed after initialization.

Effective final means a variable that has not been declared final but haven't been reassigned the value after initialization.

First is the regulation that restricts the reassignment and will raise a compilation error if we try to do so. Second is the outcome without the restriction.

Effective Final is the eventual treatment of the variable that is required for many features. For eq - Java 8 requires that

local variables referenced from a lambda expression must be final or effectively final

It means all local referenced from lambda expressions must be such that their value shouldn't be changed after initialization whether declared final or not.