Multiple choice

class sample7 { public static void main(String []args) { int []a1 = {1, 2, 3, 4, 5}; int []a2 = {1, 2, 3, 4, 5}; System.out.println("a1 == a2 is" + (a1 == a2)); System.out.println("a1.equals(a2) is" + a1.equals(a2)); System.out.println("Arrays.equals(a1, a2) is" + java.util.Arrays.equals(a1, a2)); } }

Which of the following options provides the output of this program when executed?

  1. a1 == a2 is falsearr1.equals(arr2) is falseArrays.equals(a1, a2) is true

  2. a1 == a2 is truea1.equals(a2) is falseArrays.equals(arr1, arr2) is true

  3. a1 == a2 is falsearr1.equals(a2) is trueArrays.equals(a1, a2) is true

  4. a1 == a2 is truea1.equals(a2) is trueArrays.equals(a1, a2) is false

  5. a1 == a2 is truea1.equals(a2) is trueArrays.equals(a1, a2) is true

Reveal answer Fill a bubble to check yourself
A Correct answer
Explanation

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 arrayobject, 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.