OCP Question 100, Explanation

Given in ForrestGump.java:

String str = "I been a idiot since I was born. My IQ is near 70, which qualifies me, so they say.";   // line n1
Optional<String> result = Stream.of(str.split("[ ,.]")).anyMatch(x->x.startsWith("I"));               // line n2
System.out.println(result.get());                                                                     // line n3

Which one of the following statements is correct?

A. The code prints either I or IQ.
B. The code always prints I.
C. The code prints I if lines n2 and n3 are changed to:

String result = Stream.of(sentence.split("[ ,.]")).anyMatch(x->x.startsWith("I"));                  // line n2
System.out.println(result.get());                                                                   // line n3

D. The code prints either I or IQ if lines n2 and n3 are changed to:

Optional<String> result = Stream.of(str.split("[ ,.]")).parallel().anyMatch(x->x.startsWith("I"));  // line n2
System.out.println(result.get());                                                                   // line n3

E. The code fails to compile.

 

The correct answer is E.

 

The String class’s split() needs a regular expression as its argument although regexes are not on our exam (ref.to the official list of 1Z0-809 Exam Objectives). Surprisingly enough, I did meet such a question but the regex in it was very simple and contained, if I’m not mistaken, just a single pipe symbol. On the other hand, the OCP exam for Java 7 (that is, 1Z0-804) does list a split(regex) as one of its objectives, so it appears that the question was sort of recycled from the previous exam version.

Which is actually not at all important because the Problem tests us on the use of stream operations rather then split() or even Optional. You see, all three match-related methods in Stream are supposed to return a boolean:

Consequently, line n2 doesn’t even compile, and since none of the available options provide us with a valid alternative, the correct answer to this Problem is E.

Mnemonics: a match… football… ball… In my eyes, these words are related closely enough to let me remember that allMatch(), anyMatch() and noneMatch() are the only methods in the Stream interface that return a ball… oops! a boolean.

Leave Comment

Your email address will not be published.