aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes scjp Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "scjp " Watch "scjp " New topic
Author

scjp

Vinod kashid
Greenhorn

Joined: Oct 18, 2013
Posts: 4
i have problem with following code
String[] arr = {"java", "champ", "you"};
System.out.print(Arrays.binarySearch(arr, "java"));
System.out.print(Arrays.binarySearch(arr, "You"));

please explain output of above code.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Vinod kashid wrote:i have problem with following code
String[] arr = {"java", "champ", "you"};
System.out.print(Arrays.binarySearch(arr, "java"));
System.out.print(Arrays.binarySearch(arr, "You"));

please explain output of above code.


Since the binarySearch() method requires that the array be sorted -- doing a search on an unsorted array, may or may not work.... so, are you saying that it works in some cases, and doesn't in others?

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Vinod kashid
Greenhorn

Joined: Oct 18, 2013
Posts: 4
Henry Wong wrote:
Vinod kashid wrote:i have problem with following code
String[] arr = {"java", "champ", "you"};
System.out.print(Arrays.binarySearch(arr, "java"));
System.out.print(Arrays.binarySearch(arr, "You"));

please explain output of above code.


Since the binarySearch() method requires that the array be sorted -- doing a search on an unsorted array, may or may not work.... so, are you saying that it works in some cases, and doesn't in others?

Henry


when i run this code i got output as -3 -1.
but when String[] arr = {"you", "champ", "java"}; output is 2 -1.
here arr[] is also unsorted .
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Vinod kashid wrote:
when i run this code i got output as -3 -1.
but when String[] arr = {"you", "champ", "java"}; output is 2 -1.
here arr[] is also unsorted .



With the array unsorted, it is *broken*. It may or it may not work. And as mentioned in the previous post, you can find examples that work, and you can find examples that won't work.

Henry
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: scjp