</>

Technology

Core Java

Difficulty

Beginner

Interview Question

What is the difference between ArrayList and Array in Java?

Answer

ArrayList vs Array in Java

Array

A fixed-size, indexed collection that can hold primitives or objects.

Java
// Declaration and initialization
int[] numbers = new int[5];          // fixed size 5
String[] names = {"Alice", "Bob", "Charlie"};

// Access
System.out.println(names[0]);  // "Alice"
numbers[0] = 10;

// Size is fixed — cannot add/remove
// names[3] = "Dave";  // ArrayIndexOutOfBoundsException if size was 3

// Iterate
for (String name : names) {
    System.out.println(name);
}

System.out.println(names.length);  // 3 — property, not method

ArrayList

A dynamic, resizable list from the Collections Framework. Holds only objects (uses autoboxing for primitives).

Java
import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();

// Add elements
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add(1, "Dave");   // insert at index 1

// Access
System.out.println(names.get(0));  // "Alice"

// Size grows automatically
System.out.println(names.size());  // 4 — method

// Remove
names.remove("Bob");    // remove by value
names.remove(0);        // remove by index

// Check
System.out.println(names.contains("Alice")); // true

// Iterate
for (String name : names) {
    System.out.println(name);
}

Comparison Table

FeatureArrayArrayList
SizeFixed at creationDynamic (grows/shrinks)
Primitives✅ int[], double[]❌ Must use Integer, Double
Add elementNot possible.add()
Remove elementNot possible.remove()
Length/Size.length (property).size() (method)
PerformanceFaster (direct memory)Slightly slower (overhead)
Type-safeYesYes (with generics)
Part ofCore JavaCollections Framework
Multi-dimensional✅ int[][]❌ (use List<List<>>)

When to Use Which

  • Array: Fixed number of elements, primitives, performance-critical code
  • ArrayList: Unknown/changing number of elements, need add/remove operations

In Automation Testing

Java
// Array — fixed test data
String[] browsers = {"chrome", "firefox", "edge"};

// ArrayList — dynamic collection of WebElements
ArrayList<String> actualOptions = new ArrayList<>();
List<WebElement> dropdownOptions = driver.findElements(By.tagName("option"));
for (WebElement opt : dropdownOptions) {
    actualOptions.add(opt.getText());
}
assertTrue(actualOptions.contains("New York"));

Follow AutomateQA

Related Topics