Difficulty: Easy
Correct Answer: An array has a fixed size and can hold primitives or objects, while an ArrayList is resizable at runtime, holds only objects, and provides many utility methods such as add, remove, and contains.
Explanation:
Introduction / Context:
Arrays and ArrayList are both used to store collections of elements in Java, but they differ significantly in flexibility and capabilities. This question checks whether you understand the main differences regarding size behaviour, what they can store, and what operations are available out of the box.
Given Data / Assumptions:
Concept / Approach:
An array in Java has a fixed length chosen at creation time; once created, it cannot grow or shrink. Arrays can store either primitive values such as int and double or object references. ArrayList is a resizable array backed implementation that stores only object references and automatically grows as you add elements. It provides many convenience methods such as add, remove, get, set, size, and contains. Because primitives cannot be stored directly in an ArrayList, they are wrapped in their corresponding wrapper classes when needed.
Step-by-Step Solution:
Step 1: When you declare int[] nums = new int[5]; you create an array of length five that will always have length five.Step 2: When you declare ArrayList
Verification / Alternative check:
Running small experiments shows that attempting to access an index beyond the fixed array length throws an ArrayIndexOutOfBoundsException, and you cannot simply increase the array length. By contrast, calling list.add on an ArrayList continues to work as long as memory permits. Inspection of the ArrayList documentation confirms that it stores elements as Object references and does not allow primitive storage without boxing.
Why Other Options Are Wrong:
Option B incorrectly claims that arrays are always slower and that ArrayList can hold primitives directly, which is not accurate because ArrayList stores only objects. Option C reverses the dynamic behaviour, claiming ArrayList is fixed and arrays are resizable, which is the opposite of reality. Option D equates arrays and ArrayList, ignoring clear language and library differences.
Common Pitfalls:
Developers sometimes choose ArrayList for primitive heavy data and do not account for the overhead of boxing, leading to higher memory use. Another pitfall is sticking with arrays for dynamic collections and manually resizing them instead of using ArrayList or other collections. Understanding the trade offs helps you choose arrays when you need tight control and performance and ArrayList when you need flexibility and convenient methods.
Final Answer:
An array has a fixed size and can store primitives or objects, whereas an ArrayList is a resizable collection that stores only objects and offers rich methods such as add, remove, and contains.
Discussion & Comments