Return to site

☕🎓JAVA CERTIFICATION QUESTION: takeWhile/doWhile

· java,ocp

Given the following method fragment

Which statement is correct? Choose one.

A. Line 1 will cause an error.

B. Replacing the second statement with the following code would produce the same output:

C. Replacing the second statement with the following code would produce the same output:

D. The code may print 0.

E. The code may print 7.

F. The code always prints 2.

#java #certificationquestion #ocp

Answer:

The dropWhile method, when applied to an ordered stream, starts at the beginning of the stream and tests, in order, data items of the stream it’s reading from.

If elements pass the test, they are dropped.

So far, this behavior seems similar to that of the filter method, except the behavior removes items that pass the test rather than keeping items that pass the test.

However, as soon as an item fails the test, dropWhile becomes a simple pass-through, and all subsequent items will continue down the stream without being tested.

The documentation describes this as “dropping the longest prefix of elements.”

The behavior of the takeWhile operation has parallels to this, except that the resulting stream ends as soon as any item in the stream fails the test specified in the predicate.

This is all very nice, except for two problems.

First, the order of items drawn from most Set objects is not guaranteed and typically does not match the order in which the items were added to the set.

The second problem is you don’t have an ordered stream and as mentioned, the discussion above applies only to ordered streams.

If this stream is unordered, and some (but not all) elements of this stream match the given predicate,

then the behavior of the dropWhile/takeWhile is nondeterministic; it is free to drop any subset of matching elements (which includes the empty set).

In this quiz question, you have an unordered stream; therefore, you have no basis for making reliable predictions about what it will do.

Therefore, it clearly is permissible for the operation to result in zero surviving elements, which would produce a count of 0.

So the answer is D.