What is the result?

Given:

import java.util.*;

public class SearchText {

public static void main(String[] args) {

Object[] array1 = new Object[3];

array1[0] = “foo”;

array1[0] = 1;

array1[0] = ‘a’;

int index = Arrays.binarySearch(array1, “bar”);

System.out.println(index);

}

}

What is the result?

Given:

import java.util.*;

public class SearchText {

public static void main(String[] args) {

Object[] array1 = new Object[3];

array1[0] = “foo”;

array1[0] = 1;

array1[0] = ‘a’;

int index = Arrays.binarySearch(array1, “bar”);

System.out.println(index);

}

}

What is the result?

A.
� 1

B.
0

C.
2

D.
Compilation fails

E.
An exception is thrown at runtime

Explanation:
The code compiles fine.
An exception is thrown at runtime due to data type comparison mismatch:
Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Integer.java:52)
at java.util.Arrays.binarySearch0(Arrays.java:1481)
at java.util.Arrays.binarySearch(Arrays.java:1423)
at searchtext.SearchText.main(SearchText.java:22)

Note:binarySearch

public static int binarySearch(char[] a,
char key)

Searches the specified array of chars for the specified value using the binary search algorithm. The array must be sorted (as by the sort method, above) prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.
Parameters:
a – the array to be searched.
key – the value to be searched for.
Returns:
index of the search key, if it is contained in the list; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the list: the index of the first element greater than the key, or list.size(), if all elements in the list are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.



Leave a Reply 3

Your email address will not be published. Required fields are marked *


hafid

hafid

E
java.lang.NullPointerException
because only one element of list is initialized : element [0]
elements [1] and [2] equals null

GoodLuck

GoodLuck

Even if 1 and ‘a’ is correctly initialzed to element[1] and [2], there will still be an exception.

Object[] array1 = new Object[3];

array1[0] = “foo”;

array1[1] = 1;

array1[2] = ‘a’;

int index = Arrays.binarySearch(array1, “bar”);

System.out.println(index);

produces

Exception in thread “main” java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
at java.lang.Integer.compareTo(Integer.java:52)
at java.util.Arrays.binarySearch0(Arrays.java:1481)
at java.util.Arrays.binarySearch(Arrays.java:1423)
at testapp02.TestApp02.Test3(TestApp02.java:100)
at testapp02.TestApp02.main(TestApp02.java:34)

pavan

pavan

E

Code is not typeSafe, i will throw RunTime exception