Win a copy of Spark in Action this week in the Open Source Projects forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

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

 
Bartender
Posts: 3993
156
  • 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?
 
author & internet detective
Posts: 40035
809
Eclipse IDE VI Editor Java
  • 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!
 
I don't even know how to spell CIA. But this tiny ad does:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic