# Sybex OCAJP 8 (B&S) chapter 3 review question 22

Piet Souris

Rancher

Posts: 1542

33

posted 2 weeks 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 2 weeks 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] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]

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