Local variables inside Lambda Expressions

Java 11 Certification Practice (For the complete list of practice questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/)

Can we declare local variables inside a lambda expression?

Yes, local variables can be declared inside a lambda expression. For example, the variable z is locally declared.

(x, y) -> {
			int z= x + y;
			System.out.println("Sum " + z);

Can a variable that is already in scope be redeclared as a local variable inside a lambda expression?

No, Java doesn’t let you create a local variable with the same name as one already declared in that scope. Here is an example.

(x, y) -> {
			int x= x + y;
			System.out.println("Sum " + x);

Here x is the method parameter and a compiler error occurs here as it cannot be redeclared.

Can lambda expressions access local variables from surrounding code?

Method parameters and local variables can be referenced can be referenced from lambda expressions only if they are effectively final. This means that the value of the variable cannot be updated from within the lambda expression.

Here is an example, that will help you understand this better.

	int count = 0;
	List<Integer> numList = IntStream.rangeClosed(0, 5).boxed().map(x -> {
		if (x % 2 == 0) {
			return x / 2;
		return x;

The above code does not compile because there is an attempt in the code to modify the local variable count.


For practice questions on this topic, click here.



Leave a Reply

Your email address will not be published. Required fields are marked *