Arrays in Java
Introduction
An array in Java is a container object that holds a fixed number of values of a single type. It is one of the most fundamental data structures used to store collections of data efficiently in contiguous memory locations.
Core Concepts
- Fixed Size: Once an array is created, its length cannot be changed.
- Same Data Type: All elements in an array must be of the exact same type (primitive types like
int,doubleor object references likeString,CustomClass). - Contiguous Memory: Arrays store elements in contiguous memory locations, which allows for fast, constant-time access using indices.
- Zero-Indexed: In Java, array indexing starts at 0. If an array has a size of , the valid indices are to .
Basic Operations
1. Declaration
You can declare an array by specifying the data type followed by square brackets [].
int[] myNumbers; // Recommended Java style
String myStrings[]; // Alternative style (C/C++ style), less common in Java
2. Initialization and Allocation
You must define the size of the array when you allocate memory for it using the new keyword, or you can initialize it directly with values.
// Declaration and memory allocation (size 5)
// Elements are initialized to default values (0 for int, null for objects, false for boolean)
int[] myNumbers = new int[5];
// Declaration with inline values (Array Literal)
int[] myInitializedArray = {10, 20, 30, 40, 50};
3. Accessing and Modifying Elements
You access elements by placing the index inside the square brackets.
int[] scores = {95, 85, 75, 60, 90};
int firstScore = scores[0]; // Accessing the first element (95)
scores[2] = 100; // Modifying the third element from 75 to 100
4. Finding Length
Every array has a built-in .length property (not a method, so no parentheses) that returns the number of elements the array can hold.
int size = scores.length; // Returns 5
Common Mistakes & Exceptions
-
ArrayIndexOutOfBoundsException: Attempting to access an index outside the valid range (e.g., negative index or index length) will throw an exception at runtime.int[] arr = new int[3]; System.out.println(arr[3]); // THROWS ArrayIndexOutOfBoundsException! Valid indices are 0, 1, 2. -
Fixed Size Limitation: Forgetting that arrays cannot be resized. If you need a collection that can grow or shrink dynamically, use
ArrayListfrom thejava.utilpackage instead of a standard array.
Advanced Tip: Multi-dimensional Arrays
Java supports arrays of arrays, commonly used to represent 2D matrices.
// A 2D array with 3 rows and 4 columns
int[][] matrix = new int[3][4];
// Inline initialization
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
System.out.println(grid[1][2]); // Output: 6