Given the following code fragment:
hich output is guaranteed? Choose one.
* None of the above
#java #certificationquestion #ocp
Answer: None of the above
This question explores the Java API for the java.util.Arrays class, specifically the compare() and mismatch() methods.
Javadoc for compare:
public static int compare(int a, int b)
Compares two int arrays lexicographically.
It returns the value 0 if the first and second array are equal and contain the same elements in the same order;
a value less than 0 if the first array is lexicographically less than the second array;
and a value greater than 0 if the first array is lexicographically greater than the second array.
Note that the Javadoc states "value less than 0" and "value greater than 0".
So Arrays.compare(a1, a2) should return a value greater than 0,
and Arrays.compare(a3, a2) should return a value less than 0.
In the answer "1-1-11", the first two values match but does not guarantee the output.
Actually, a valid JDK or JRE could have a library implementation that returns values other than +1 and -1 from the compare method.
Let's check the mismatch statements.
Javadoc for mismatch:
public static int mismatch(int a, int b)
Finds and returns the index of the first mismatch between two int arrays, otherwise return -1 if no mismatch is found.
Given these rules, the output of the mismatch operation with both arguments provided as in array a1 must be -1.
The output of the mismatch operation with the arguments for array a2 and array a1 will be 1,
because the index contains the values 23 and 24.
This is consistent with option "1-1-11".
So the answer "1-1-11" is compliant but does not guarantee to be output for any JDK implementing with values other than +1 and -1 from the compare method
So the right answer is "None of the above".