Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › Control Flow — Loops, Conditionals & Switch

How do you correctly compare the contents of two arrays, and why doesn't == work?

Level I · BeginnerControl Flow — Loops, Conditionals & Switch
Short answer

Use Arrays.equals(a, b) for one-dimensional arrays (or Arrays.deepEquals for nested arrays).

Explanation

The == operator and the default Object.equals compare references -- whether the two variables point to the SAME array object -- not their contents, so two different arrays with identical elements are '!=' and equals() returns false. Arrays.equals walks the elements and compares them pairwise, which is what you almost always want.

Common mistakes
  • Comparing arrays with == or equals() instead of Arrays.equals / Arrays.deepEquals.
  • Forgetting nested arrays need deepEquals.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for Control Flow — Loops, Conditionals & Switch.

Practise free

More on Control Flow — Loops, Conditionals & Switch