When you need to store multiple values of the same type in a single container, Java offers arrays. They function similarly to Python’s lists but are more rigid: once created, an array cannot grow or shrink. If you need a flexible, resizable structure, Java provides other collections (ArrayList), but those come later.
In this section, we’ll learn how to declare, create, and use arrays in Java, see how arrays interact with loops, and examine the most common mistakes (like out-of-bounds errors and confusion over default initialization). Understanding these basics will prepare you for more advanced data structures later in the course.
An array in Java is a fixed-size sequence of elements of the same type, all stored contiguously in memory. Each element is accessed by an index, starting at 0 and going up to length - 1.
Valid indices here are 0,1,2,3,4. Trying arr[5] or arr[-1] would cause an error. Next, let’s see how to declare and initialize an array in actual Java code.
// Step 1: Declaration
int[] numbers; // 'numbers' is an array of int, but not yet created
// Step 2: Allocation
numbers = new int[5]; // now 'numbers' refers to an array of length 5
You can combine these steps in one line: int[] numbers = new int[5]; This means you have space for 5 int elements: numbers[0], numbers[1], ..., numbers[4]. Each of these starts out at 0.
int[] primes = {2, 3, 5, 7, 11};
// This implicitly sets the array's length to 5.
Note that you cannot assign like this after declaring: int[] primes; primes = {2, 3, 5, 7, 11}; // Error outside the declaration line Instead, you must do it all at once or manually assign each element later.
Attempting squares[4] or squares[-1] will cause an ArrayIndexOutOfBoundsException at runtime. This is a protective measure in Java—accessing outside valid indices is never allowed, preventing more obscure bugs or memory corruption.
When you do new int[5], Java allocates memory for 5 integers, all initially 0. If it’s an array of double, each element starts as 0.0; for boolean, it’s false.
For object references (e.g., String[]), each element starts as null. That means you can’t call methods on arr[i] until you assign an actual object to arr[i]. For example:
String[] names = new String[3];
// names[0], names[1], names[2] are all null initially
names[0] = "Alice"; // now names[0] refers to "Alice"
names[1] = "Bob"; // now names[1] refers to "Bob"
If you accidentally do names[0].length() before assigning names[0], you’ll get a NullPointerException.
In Java, an array is itself a special kind of object. That means if you write int[] arr = new int[5], behind the scenes, arr is a reference to an array object stored on the heap. A subtle but common confusion arises when you do something like this:
int[] arr1 = new int[3];
int[] arr2 = arr1; // arr2 now points to the same array object as arr1
arr1[0] = 99;
System.out.println(arr2[0]); // Will print 99, not 0!
Because arrays are objects, arr1 and arr2 both reference the same underlying array. Changing an element via arr1 also changes what arr2 sees. There is no automatic "deep copy"—if you want a separate copy, you’d need to create another array and copy over elements manually or use library methods like Arrays.copyOf (which we’ll discuss later).
Index Out of Bounds: If your array is length 5, valid indices are 0..4. Trying arr[5] or arr[-1] yields ArrayIndexOutOfBoundsException. Double-check your loop boundaries and conditions carefully.
Fixed Size: Once you do new int[5], you can’t change it to 10 elements. If you need a dynamically sized collection, you’ll learn about ArrayList or other collections soon.
Null Elements (for reference types): String[] words = new String[3] starts with all elements null, meaning you must assign actual strings before using them. Otherwise, you’ll get a NullPointerException.
Subsection4.4.7Interactive Exercises: Working with Arrays
Let’s solidify these concepts with a few exercises. Each will help you get comfortable declaring arrays, updating elements, and iterating over them with loops.
Exercise 1: Basic Array Print Declare an int[] named numbers of length 4, then assign the values 2, 4, 6, 8. Finally, print each element (in a for loop) to verify.
Exercise 2: Summation of an Array Create an array of 5 integers: 10, 20, 30, 40, 50. Use a loop to sum them up, then print the result. (Hint: Start sum at 0 and accumulate.)
Declaration & Allocation: int[] arr = new int[5] sets up memory for five integers, all initially 0. Arrays are objects, so arr is a reference to the actual data.
Arrays of References: String[] words starts out with all null if you do new String[...]. You must assign objects to each element or you’ll get NullPointerException if you call methods on words[i].
Going forward, we’ll use arrays with loops to handle all kinds of data. Next, we’ll discuss how to build a custom class that acts like a collection, so we can introduce the for-each loop as “syntactic sugar” for iterating over arrays or other collections.