Lesson 5 / 11

Arrays and ArrayLists

Arrays — fixed size

String[] courses = {"Python", "Java", "SQL"};
System.out.println(courses[1]);   // Java
System.out.println(courses.length);   // 3 -- note: length, not length(), no parentheses

A Java array’s size is fixed the moment it’s created — there’s no way to add a fourth item to courses above without creating an entirely new, larger array. This limitation is exactly why ArrayList exists.

ArrayList — resizable

import java.util.ArrayList;

ArrayList<String> courses = new ArrayList<>();
courses.add("Python");
courses.add("Java");
courses.remove("Python");
System.out.println(courses.get(0));   // Java
System.out.println(courses.size());   // 1 -- note: size(), not length

Use a plain array when the size is fixed and known in advance — like the days of the week. Use ArrayList when items get added or removed at runtime — most real code reaches for ArrayList because that’s the far more common situation in practice.

Looping over a collection

for (String course : courses) {
    System.out.println(course);
}

This is called an enhanced for loop, or “for-each” loop — it visits every item in the collection without you managing an index manually, and it works identically on both arrays and ArrayList.

A common mistake

Trying to store a primitive type like int directly in an ArrayList won’t compile — ArrayList only holds objects, not primitives. Java automatically converts (“autoboxes”) an int to its object wrapper Integer when needed, which is why ArrayList<Integer> works even though there’s no ArrayList<int>.