Local Variables and Lambda Expressions – Practice Questions

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

Topic: Working with Streams and Lambda

To learn more about this topic, visit http://talks.skilltoz.com/local-variables-inside-lambda-expressions/

Practice Questions (Answers below)

1. What will be the result of compiling and running this program?
		List<Integer> numList = IntStream.range(0, 5).boxed().map(x -> {
			int i = 0;
			if (x % 2 == 0) {
				i=i+1;
				return x / 2;
			}
			return x;
		}).collect(Collectors.toList());
		System.out.println(i);
	

Choices

A. Does not compile
B. Exception at runtime
C. Prints 3

2. What will be the result of compiling and running this program?
	int count = 0;
	List<Integer> numList = IntStream.rangeClosed(0, 5).boxed().map(x -> {
			if (x % 2 == 0) {
				count++;
				return x / 2;
			}
		    return x;
		}).collect(Collectors.toList());
	System.out.println(count);
    

Choices

A. Does not compile
B. Exception at runtime
C. Prints 3

Answers

  1. Choice A is correct. The variable i is declared within the lambda expression and hence it cannot be accessed outside the lambda. In this case, there is an attempt to print the value of i after the lambda expression is closed. Hence, the compiler gives an error.
  2. Choice A is correct. 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. In this case, there is an attempt to increment the variable count within the lambda expression. Hence the code does not compile.

Reference

http://talks.skilltoz.com/local-variables-inside-lambda-expressions/

Leave a Reply

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