nerdexam
Oracle

1Z0-809 · Question #60

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…

The correct answer is A. 0. Option A is correct because str.indexOf("Java") returns 0 - Java uses zero-based indexing, and the substring "Java" begins at the very first character of "Java is a programming language". Option B (1) is wrong because Java string indices start at 0, not 1; confusing zero-based…

Question

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?

Options

  • A0
  • B1
  • CA compilation error occurs at line n1.
  • DA compilation error occurs at line n2.

How the community answered

(26 responses)
  • A
    85% (22)
  • B
    8% (2)
  • C
    4% (1)
  • D
    4% (1)

Explanation

Option A is correct because str.indexOf("Java") returns 0 - Java uses zero-based indexing, and the substring "Java" begins at the very first character of "Java is a programming language".

Option B (1) is wrong because Java string indices start at 0, not 1; confusing zero-based with one-based indexing is the classic trap this distractor is baiting.

Option C is wrong because the method reference str::indexOf is perfectly valid - String.indexOf(String) accepts a String and returns an int, which matches ToIntFunction<String>'s abstract method signature int applyAsInt(String t) exactly.

Option D is wrong because applyAsInt("Java") is the correct way to invoke a ToIntFunction<String>, and passing a String literal is valid, so no compilation error occurs.

Memory tip: When you see a method reference bound to a specific instance (object::method), mentally substitute it as a lambda - str::indexOf is equivalent to s -> str.indexOf(s). Ask yourself: does the parameter type and return type match the functional interface? If yes, it compiles. And always remember: indexOf at position zero returns 0, not 1.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice