While studying for OCP 8 certification (upgrade from OCP 7), I was exploring some “what if’s” and came across something that I haven’t seen among the mock exam questions I took and that might be of mild amusement to some (though veterans will probably just think “Well duh, that’s obvious!”). Since I’m unlikely to ever come up with more than a few questions I can offer the world, and the one below would probably not be used in a real exam anyway, I’m starting this thread for myself and anyone else who wants to deposit similar trivia. I couldn’t see a similar thread or related section in which to put this, but mods please feel free to move it if there is, or e.g. to the main Java section if more appropriate. Also, corrections of any misinterpretations I may post are welcome
Update: After I posted, the system alerted me to a series of posts from 12 years ago with a similar tack, started by Valentin Crettaz, which can be found by searching for "SCJP Brainteaser"
posted 2 weeks ago
Q1: Java 8 Stream methods (OCP)
Which statement is true of the following code snippet (choose one):
(A) A list of the numbers is always printed
(B) An exception is thrown
(C) It does not compile
(D) None of the above
I don’t see an option for spoiler tags, so I’m writing the answer/comment in white text three lines below to make it less easily viewable 'by accident', i.e. without mouseover selection /copy-paste; if this doesn’t work well enough, I’ll rearrange.
Answer: D. Assuming the stream is processed in parallel (split between two or more threads), as it usually will be on multi-core systems, I assume, a nested list of lists will be generated. E.g. I see [1, , [3, [4, ]]] on my system. This is because the List method add(...) was used as third arg to collect(...) instead of addAll(...). Of course, this is unlikely to ever be done in a real program, where one would usually want to generate a simple list of the Integers by allowing parallel-processed lists to be combined to [1, 2, 3, 4, 5] by dumping their contents together using addAll(...), the stream is parallel, the order of the Integers could be different, though I always happen to get them in order. And of course, if a properly generically-typed list reference is used, i.e. List<Integer>, the statement does not even compile, as the combiner cannot add List<Integer> to List<Integer>; by contrast, the combiner can add one ‘raw’ List (of Objects) to another, as the added List simply goes in as an Object, generating a nested Lists of Lists.