Core java interview Questions You'll Most Likely Be Asked (Second Edition)


Give an example of static method reference


Download 1.52 Mb.
Pdf ko'rish
bet87/171
Sana07.01.2023
Hajmi1.52 Mb.
#1081886
1   ...   83   84   85   86   87   88   89   90   ...   171
Bog'liq
Core JAVA Interview Questions Youll M...

Give an example of static method reference.
Answer:
Static method reference occurs when a static method of a class
is accessed via the method reference operator. The following
code demonstrates this:
public class MethodReferenceDemo {
public static boolean checkIfNumberGreaterThan8(int
num) {
return num > 8;
}
public static void main(String[] args) {
Predicate numberChecker =


230.
MethodReferenceDemo::checkIfNumberGreaterThan8;
boolean flag = numberChecker.test(10);
}
}
Here, the MethodReferenceDemo class has a static method
called checkIfNumberGreaterThan8(). This checks if the
input number is greater than 8 and returns a boolean value
accordingly. In the main method, a Predicate is defined.
However, instead of using a lambda expression to implement the
Predicate, the existing checkIfNumberGreaterThan8() is
referenced via the method reference operator. Since
checkIfNumberGreaterThan8() is a static method, the class
name followed by method name is used.
Consider the following Shape class:
public class Shape {
private String name;
}
What changes are required in this class in order to make the
code below valid?
List shapeNames =
Arrays.asList(“Circle”,”Triangle”);
List shapes =
shapeNames.stream().map(Shape::new).collect(Collectors.t
oList());
Answer:
The code above creates a List of String values called
shapeNames. It then uses the Stream map() operation to create


231.
a List of Shape objects called shapes. The code uses a
constructor reference to create a new Shape object using the
String shape name. So, the Shape class requires a constructor
that accepts a String value as input as follows:
public Shape(String name) {
this.name = name;
}

Download 1.52 Mb.

Do'stlaringiz bilan baham:
1   ...   83   84   85   86   87   88   89   90   ...   171




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling