Given the code fragment:

String str = "Java is a programming language";
ToIntFunction<String> indexVal = str::indexOf; //line n1
int x = indexVal.applyAsInt("Java"); //line n2
System.out.println(x);

What is the result?

A.

0

B.

1

C. A compilation error occurs at line n1.
D. A compilation error occurs at line n2.

题解

ToIntFunction 的 JDK 源代码如下:

@FunctionalInterface
public interface ToIntFunction<T> {

    int applyAsInt(T value);
}

所以 line n2,其实会等于:

int x = str.indexOf("Java");

会在 str 所参考到的字符串中,索引 0 的位置找到「Java」子字符串。