What Are Arrays in Java?
An array in Java is a collection of elements of the same data type, stored at contiguous memory locations. Arrays are used to store multiple values in a single variable, rather than declaring separate variables for each value. Arrays provide an efficient way to organize and manipulate large sets of data.
Key Features of Java Arrays
- Fixed Size:
- Once an array is created, its size cannot be changed.
- Homogeneous Elements:
- All elements in an array must be of the same data type (e.g., integers, strings, floats).
- Zero-Based Indexing:
- The index of the first element is 0, and the last element is length – 1.
- Random Access:
- You can access any element directly using its index.
- Efficient Storage:
- Arrays store data in contiguous memory, making access and modification faster.
Types of Arrays in Java
- Single-Dimensional Array:
- Contains elements in a single row.
- Multi-Dimensional Array:
- Contains elements in a grid-like structure (e.g., matrices).
Declaring and Initializing Arrays
1. Declaring an Array
dataType[] arrayName;
- dataType: Type of data the array will store (e.g., int, String).
- arrayName: Name of the array variable.
2. Allocating Memory for an Array
arrayName = new dataType[size];
- size: Number of elements the array will hold.
3. Declaring and Initializing Together
int[] numbers = new int[5]; // Array of size 5
You can also initialize an array with values:
int[] numbers = {1, 2, 3, 4, 5};
Single-Dimensional Array Example
public class ArrayExample {
public static void main(String[] args) {
// Declare and initialize an array
int[] numbers = {10, 20, 30, 40, 50};
// Access and print array elements
for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}
}
}
Output:
Element at index 0: 10
Element at index 1: 20
Element at index 2: 30
Element at index 3: 40
Element at index 4: 50
Multi-Dimensional Array Example
Multi-dimensional arrays are arrays of arrays. The most common type is a 2D array.
Declaration
dataType[][] arrayName = new dataType[rows][columns];
Initialization
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Accessing Elements
public class MultiDimensionalArray {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Print each element of the matrix
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println(); // New line after each row
}
}
}
Output:
1 2 3
4 5 6
7 8 9
Common Array Operations
1. Finding the Length of an Array
Use the length property to determine the size of an array.
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Array length: " + numbers.length);
Output:
Array length: 5
2. Updating Array Elements
int[] numbers = {10, 20, 30};
numbers[1] = 25; // Update the second element
System.out.println(numbers[1]); // Output: 25
3. Copying an Array
You can use the System.arraycopy() method to copy arrays.
int[] original = {1, 2, 3};
int[] copy = new int[original.length];
System.arraycopy(original, 0, copy, 0, original.length);
Enhanced For Loop with Arrays
The enhanced for loop simplifies array traversal.
public class EnhancedForLoop {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};
// Use enhanced for loop
for (int num : numbers) {
System.out.println(num);
}
}
}
Output:
10
20
30
40
Advantages of Arrays
- Easy Access:
- Retrieve elements quickly using indices.
- Efficient Storage:
- Contiguous memory allocation minimizes overhead.
- Simplified Management:
- Groups related data together for better organization.
Limitations of Arrays
- Fixed Size:
- Once created, the size of an array cannot be changed.
- Homogeneous Data:
- All elements must be of the same type.
- No Built-In Methods:
- Arrays lack advanced methods available in collections like ArrayList.
Common Errors with Arrays
ArrayIndexOutOfBoundsException:
- Occurs when trying to access an index outside the valid range.
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // Error
NullPointerException:
- Occurs when working with an uninitialized array
int[] numbers = null;
System.out.println(numbers.length); // Error