✏️ Explanatory Question

[String and Arrays]

Question:

Find the output of the following snippet:

void check1()
{
    String x[] = {"Kolkata","Chennai","Delhi"};
    String y[] = {"Kolkata","Chennai","Delhi"};

    System.out.println(x.equals(y));
}

Answer:

false

👁 4 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Explanation:

In Java, arrays are objects.

The method:

x.equals(y)

does NOT compare the contents of the arrays. Instead, it compares the references (memory addresses) of the arrays.

Here:

  • x and y are two different array objects
  • Both arrays contain same elements
  • But they are stored in different memory locations

Therefore:

x.equals(y)

returns:

false

Important Concept:

  • For arrays, equals() checks reference equality
  • To compare array contents, use:
Arrays.equals(x, y)

Conclusion:

  • x and y have same contents ✅
  • x and y are different objects ✅
  • Hence output = false