C

Core Java tutorial for beginners

Clean • Professional

Java Arrays – Common Pitfalls in Java Arrays

2 minute

Common Pitfalls in Java Arrays

Arrays are powerful, but beginners often encounter mistakes when using them. Knowing these common pitfalls will help you write bug-free and efficient code.


1. ArrayIndexOutOfBoundsException

Occurs when you access an index that doesn’t exist in the array.

public class OutOfBoundsExample {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3};
        System.out.println(numbers[3]); //  Error
    }
}

Error : Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3


2. Null Arrays

If an array reference points to null, any operation will throw a NullPointerException.

public class NullArrayExample {
    public static void main(String[] args) {
        int[] numbers = null;
        System.out.println(numbers.length); //  Error
    }
}
int[] numbers = new int[5]; // Correct

3. Choosing the Wrong Array Size

Arrays in Java have fixed sizes. Declaring a size too small can cause errors, too large wastes memory.

int[] scores = new int[3]; // Can only store 3 elements
scores[3] = 50; //  OutOfBounds

4. Arrays vs Collections

FeatureArrayCollection (e.g., ArrayList)
SizeFixedDynamic (can grow/shrink)
TypeCan store primitivesStores objects only
PerformanceFaster (less overhead)Slightly slower (more flexible)
MethodsLimited (length, indexing)Many utility methods (add, remove, sort, contains)

Common mistake: Using arrays when a dynamic structure is needed, or using ArrayList when performance-critical.


5. Mixing Types

Arrays can only store a single data type. Trying to mix types leads to compilation errors.

Object[] arr = {1, "Java", true}; //  Possible with Object array
int[] numbers = {1, "2"};        //  Error

Tips to Avoid Common Pitfalls

  • Always check array bounds.
  • Initialize arrays before use.
  • Use numbers.length to control loops.
  • Choose arrays for fixed-size, primitive-heavy data.
  • Prefer Collections for dynamic and object-heavy data.
  • Avoid mixing incompatible types.

Article 0 of 0