Java Quiz: forEach Construct

Click http://talks.skilltoz.com/foreach-construct-in-java/ to learn more about using the forEach construct.

Java 11 Certification Practice Questions on forEach

Q1. Given the following list

List<String> places = Arrays.asList("New York", "London", "Sydney");

Choose the options which give the same output as the following piece of code.

for(String place:places) {
		System.out.println(place);
}

Choices

A. places.forEach(System.out::println);
B. places.forEach(String place -> System.out.println(place));
C. places.forEach(place -> System.out.println(place));
D. places.forEach(System.out::println(place));

Answer

The given piece of code uses the enhanced for loop to iterate a list. Choices A and C are both correct ways to invoke forEach, which does the same thing. Choice A uses lambda expression, while choice C uses method reference. Choices B and D will not compile as the syntax used is incorrect.

Reference

http://talks.skilltoz.com/foreach-construct-in-java/

For Java 11 Certification Exam Practice Questions, refer http://talks.skilltoz.com/java-11-certification-exam-questions/

Leave a Reply

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