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?
Click on the arrows to vote for the correct answer
A. B. C. D.A.
The code fragment declares a String variable str
and initializes it with the value "Java is a programming language". It then declares a ToIntFunction<String>
variable indexVal
and initializes it with a method reference to the indexOf
method of the str
object using the double colon (::) operator. The indexOf
method is used to find the index of the first occurrence of the specified substring in the given string.
The indexVal
function takes a String argument and returns its index in the str
object, or -1 if it is not found.
The code then declares an int variable x
and initializes it by invoking the applyAsInt
method on the indexVal
function, passing in the String "Java" as the argument. This will search for the index of the substring "Java" in the str
object using the indexOf
method.
Finally, the code prints the value of x
to the console.
Since "Java" is present at index 0 in the str
object, the output of the code will be 0, and the correct answer is A.
Therefore, the correct answer is A.