Piet Souris

Rancher

Posts: 1828

61

posted 7 months ago

- 1

For review question 22 in chapter 3 the given answer is D: "the result is undefined".

However, given how a binary search works, the outcome is always 2 here and so I opted for answer A. I see nothing about this is the errata, so if I am wrong nevertheless, what then is undefined?

However, given how a binary search works, the outcome is always 2 here and so I opted for answer A. I see nothing about this is the errata, so if I am wrong nevertheless, what then is undefined?

posted 7 months ago

Piet,

Good question. It's not in the errata because the book is correct on this point .

If you take a look at the Arrays.binarySearch JavaDoc, it includes the text:

Notice that "undefined" is not the same as "random." That's why you see deterministic behavior and always get 2. However, a future (or past or different) JDK implementation is free to return anything in this scenario. Hence undefined. This is an important distinction to notice so you get this question right on the exam.

With this particular array, you get lucky that 2 is always returned because of the implementation. It first checks the midpoint and gets a match so returns 2. But try this example:

It doesn't print 1 which shows that sorting is in fact important. Hence an undefined result.

Long story short, it just so happens that the undefined result is 2 in the example in the book!

Good question. It's not in the errata because the book is correct on this point .

If you take a look at the Arrays.binarySearch JavaDoc, it includes the text:

The array must be sorted (as by the sort(byte[]) method) prior to making this call. If it is not sorted, the results are undefined.

Notice that "undefined" is not the same as "random." That's why you see deterministic behavior and always get 2. However, a future (or past or different) JDK implementation is free to return anything in this scenario. Hence undefined. This is an important distinction to notice so you get this question right on the exam.

With this particular array, you get lucky that 2 is always returned because of the implementation. It first checks the midpoint and gets a match so returns 2. But try this example:

It doesn't print 1 which shows that sorting is in fact important. Hence an undefined result.

Long story short, it just so happens that the undefined result is 2 in the example in the book!

[OCA 8 book] [OCP 8 book] [Practice tests book] [Blog] [JavaRanch FAQ] [How To Ask Questions] [Book Promos]

Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2

Consider Paul's rocket mass heater. |