AI Hints
Home›Java Tutorial›Two-Dimensional Arrays, Common Array Mistakes, Practice: Top Scores
Java · Lesson 53 of 120

Common Array Mistakes

Traps to avoid.

⏱ 2 min read▶ Video at 1:06:16🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Arrays have a few traps. Comparing them, copying them, and empty boxes that hold null. Let's walk through each one.

  • Comparing
  • Copying
  • null boxes

Compare and copy

Two equals signs asks, is this the same array object? So two arrays with the same values aren't equal. Arrays dot equals compares the values. Writing c equals a doesn't copy the array. Both names point to the same array, so changing c changes a! Arrays dot copy of makes a real copy. Run it. Double equals is false, but equals is true. A zero became ninety nine. And a one is still two.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[] a = {1, 2, 3};
        int[] b = {1, 2, 3};
        System.out.println("a == b? " + (a == b));
        System.out.println("equal? " + java.util.Arrays.equals(a, b));

        int[] c = a;
        c[0] = 99;
        System.out.println("a[0] is now " + a[0]);

        int[] copy = java.util.Arrays.copyOf(a, a.length);
        copy[1] = 55;
        System.out.println("a[1] is still " + a[1]);
    }
}
Output
a == b? false
equal? true
a[0] is now 99
a[1] is still 2

Boxes that hold null

A new String array starts with null in every box. Box zero holds Zoe, so its length works. But box one is still null. Calling a method on null crashes. Run it. Three, then a null pointer exception.

Main.javajava
public class Main {
    public static void main(String[] args) {
        String[] names = new String[3];
        names[0] = "Zoe";
        System.out.println(names[0].length());
        System.out.println(names[1].length());
    }
}
Output
3
Exception in thread "main" java.lang.NullPointerException: Cannot invoke
"String.length()" because "names[1]" is null
    at Main.main(Main.java:6)

The traps

Here are the four array traps together. Every Java programmer hits each one, at least once.

TrapFix
Index past the enduse i < length
a == bArrays.equals(a, b)
b = a is not a copyArrays.copyOf
null boxesfill before using

Summary

Use Arrays dot equals to compare, and Arrays dot copy of to copy. Watch for null boxes, and indexes past the end. Next, a practice with top scores.

Key takeaways
  • Arrays.equals
  • Arrays.copyOf
  • Beware null
Next up: Practice: Top Scores — put module six together