Consider the following program:
public class Main { public static void main(String []args) { int []arr1 = {1, 2, 3, 4, 5}; int []arr2 = {1, 2, 3, 4, 5}; System.out.println("arr1 == arr2 is " + (arr1 == arr2)); System.out.println("arr1.equals(arr2) is " + arr1.equals(arr2)); System.out.println("Arrays.equals(arr1, arr2) is " + java.util.Arrays.equals(arr1, arr2)); }/*from w w w. jav a2 s . co m*/ }
Which one of the following options provides the output of this program when executed?
a) arr1 == arr2 is false/* w w w . java2s. c om*/ arr1.equals(arr2) is false Arrays.equals(arr1, arr2) is true b) arr1 == arr2 is true arr1.equals(arr2) is false Arrays.equals(arr1, arr2) is true c) arr1 == arr2 is false arr1.equals(arr2) is true Arrays.equals(arr1, arr2) is true d) arr1 == arr2 is true arr1.equals(arr2) is true Arrays.equals(arr1, arr2) is false e) arr1 == arr2 is true arr1.equals(arr2) is true Arrays.equals(arr1, arr2) is true
a)
The first comparison between two array objects is carried out using the == operator, which compares object similarity so it returns false here.
The equals()
method, which compares this array object with the passed array object, does not compare values of the array since it is inherited from the Object class.
Thus we get another false.
On the other hand, the Arrays class implements various equals()
methods to compare two array objects of different types; hence we get true from the last invocation.