1Z0-809 practice question 2 of 25

Given: class Student { String course, name, city; public Student (String name, String course, String city) { this.course = course; this.name = name…

Full set: 196 questions
Given: class Student { String course, name, city; public Student (String name, String course, String city) { this.course = course; this.name = name; this.city = city; } public String toString() { return course + “:” + name + “:” + city; } and the code fragment: List stds = Arrays.asList( new Student (“Jessy”, “Java ME”, “Chicago”), new Student (“Helen”, “Java EE”, “Houston”), new Student (“Mark”, “Java ME”, “Chicago”)); stds.stream() .collect(Collectors.groupingBy(Student::getCourse)) .forEach(src, res) -> System.out.println(scr)); What is the result?
Answer options
A: [Java EE: Helen:Houston][Java ME: Jessy:Chicago, Java ME: Mark:Chicago]
B: Java EEJava ME
C: [Java ME: Jessy:Chicago, Java ME: Mark:Chicago][Java EE: Helen:Houston]
D: A compilation error occurs. Correct answer
Correct Answer:
D. A compilation error occurs.
Explanation

The code will fail to compile for two primary reasons. First, the method reference Student::getCourse requires a public method named getCourse() to be present in the Student class, which is missing. The Student class only defines public fields. Second, the lambda expression in the forEach call, (src, res) -> System.out.println(scr)), contains a typo. The variable scr is not defined; the parameter name is src. Either of these issues is sufficient to cause a compilation error.

Why Incorrect

A. The code will not compile, so it cannot produce this output. This output format also does not match what a Map.forEach printing only the key would produce.
B. The code will not compile. Even if it did, printing just the keys "Java EE" and "Java ME" would require a different lambda, such as (src, res) -> System.out.print(src).
C. The code will not compile. This output is similar to A but in a different, non-guaranteed order, and is also incorrect for the same reasons.

References

1. Oracle, The Java™ Tutorials, "Method References". (docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html). This tutorial explains that method references are compact lambda expressions for methods that already have a name. The syntax ClassName::methodName requires methodName to be a method.

2. The Java® Language Specification, Java SE 8 Edition, Section 15.13, "Method Reference Expressions". This section formally defines the syntax and semantics of method references, which apply to methods and constructors, not fields.

3. The Java® Language Specification, Java SE 8 Edition, Section 15.27.1, "Lambda Parameters". This section defines the scope of lambda parameters, confirming that a variable like scr would be an "unresolved symbol" if not declared as a parameter.

Scroll to Top