• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Piet Souris
Rancher
Posts: 1542
33
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic