Skip to main content

Section 4.4 Introducing Arrays

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.

Subsection 4.4.1 What Is an Array?

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.
If you come from Python, you might think of “lists,” but Java arrays differ:
  • Rigid size: The length is set at creation time and cannot change.
  • Strict typing: All elements must match the declared type (int, double, boolean, etc.).
For instance, if you have an int[] of length 5, it might look like:
Indexes:  0   1   2   3   4
Values:  [?] [?] [?] [?] [?]
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.

Subsection 4.4.2 Declaring and Initializing Arrays

In Java, creating an array often happens in two steps:
  1. Declare a variable that will refer to an array.
  2. Allocate the actual array using new, specifying the length.
// 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.
If you already know the exact contents, you can use an initializer list:
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.

Subsection 4.4.3 Accessing and Updating Array Elements

Each element is accessed by arr[index]. In Java, arr.length (not arr.length()) reports the array’s length.
Below is a small demo that sets each element to the square of its index, then prints the results:
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.

Subsection 4.4.4 Default Values & References

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.

Subsection 4.4.5 Arrays Are Objects in Java

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).
Keep in mind:
  • arr.length is a field that stores the array’s size (no parentheses).
  • Assigning one array variable to another never copies the contents; it only copies the reference.

Subsection 4.4.6 Common Array Pitfalls

Arrays are straightforward once you get the hang of them, but here are key pitfalls:
  • 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.
  • Arrays Are Objects: If you do arr2 = arr1, both variables share the same array in memory—changes to one show up in the other.

Subsection 4.4.7 Interactive 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.

Checkpoint 4.4.1.

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.

Checkpoint 4.4.2.

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.)

Subsection 4.4.8 Summary: Introducing Arrays

Arrays in Java hold a fixed number of elements, all of the same type. Here are your key takeaways:
  • 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.
  • Initializer Lists: int[] primes = {2,3,5,7,11}; sets the length automatically to 5. You can’t use {...} syntax outside of the declaration line.
  • Indices & length: Indices go from 0 to arr.length - 1. The length field is used to ensure we stay within bounds in loops.
  • 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].
  • Shared References: arr2 = arr1 shares the same underlying array. Changing arr1[0] also affects arr2[0].
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.
You have attempted of activities on this page.