Arrays and ArrayList
A Java array has a fixed size set at creation and no built-in way to grow — array.length gives you that size directly, since unlike C arrays, a Java array always knows its own length.
Main.java
Try it yourself →public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("numbers[2] = " + numbers[2]);
System.out.println("length = " + numbers.length);
}
}Output
numbers[2] = 3 length = 5
ArrayList
ArrayList is Java's primary growable collection — it manages its own resizing as you add elements, and like all of Java's generic collections, it only holds reference types, so an ArrayList<Integer> stores boxed Integer objects rather than primitive int values directly.
Main.java
Try it yourself →import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
System.out.println(numbers);
System.out.println("size = " + numbers.size());
}
}Output
[1, 2, 3, 4] size = 4
Next: strings — String immutability, concatenation, and the difference between == and .equals().
Practice exercise
Given an ArrayList<Integer> numbers containing 4, 8, 15, 16, sum all its elements with an enhanced for loop and print the total.