Module: | Arrays, Strings & Exception Handling
Q64: Consider the following statements regarding Method References in Java:
1. The double colon (::) operator is a shorthand syntax utilized to directly pass an existing method as an argument instead of writing a verbose lambda expression.
2. The syntax ClassName::new acts as a Constructor Reference, perfectly aligning with the Supplier functional interface to instantiate new objects dynamically.
3. Method references are strictly limited to invoking static methods; attempting to reference a non-static instance method will trigger an immediate compile-time error.
Which of the above statements is/are correct?
2. The syntax ClassName::new acts as a Constructor Reference, perfectly aligning with the Supplier functional interface to instantiate new objects dynamically.
3. Method references are strictly limited to invoking static methods; attempting to reference a non-static instance method will trigger an immediate compile-time error.
Which of the above statements is/are correct?
✅ Correct Answer: A
🎯 Quick Answer:
The correct combination is 1 and 2. Statement 3 is incorrect because method references fully support instance methods. They can target a specific object's instance method (printer::print) or an arbitrary object's instance method belonging to a specific type (String::toUpperCase).Structural Breakdown: There are four structural types: Static (Math::max), Specific Instance (System.out::println), Arbitrary Instance (String::length), and Constructor (ArrayList::new). Historical/Related Context: Method references were introduced as syntactic sugar in Java 8. While s -> System.out.println(s) was already a vast improvement over legacy code, System.out::println pushed Java closer to the extreme declarative conciseness found in functional languages like Scala and Haskell.
Causal Reasoning: The compiler flawlessly translates a constructor reference like Student::new into () -> new Student() (Statement 2). If a framework requires a Supplier to dynamically generate blank objects on demand, the constructor reference provides the exact memory-allocation instruction directly to the JVM without requiring any intermediary boilerplate logic.