An array is a collection of elements of the same data type, stored in contiguous memory locations. In Java, an array allows you to store multiple values in a single variable, making it a powerful tool to manage large datasets efficiently. Each element in an array is identified by its index, which starts from 0.
Types of Arrays
Java supports different types of arrays:
Single-Dimensional Arrays: A one-row array where elements are stored in a sequential manner.
1 |
int[] arr = {1, 2, 3, 4, 5}; |
Multi-Dimensional Arrays: Arrays that contain more than one row and column, like matrices. The most common type is a 2D array.
1 2 3 4 5 |
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; |
Jagged Arrays: A special type of multi-dimensional array where each row can have different column sizes.
1 2 3 4 |
int[][] jaggedArray = new int[3][]; jaggedArray[0] = new int[2]; // First row has 2 elements jaggedArray[1] = new int[3]; // Second row has 3 elements jaggedArray[2] = new int[1]; // Third row has 1 element |
Declaration & Initialization
To use an array, we must declare and initialize it.
Declaration: Defines the array variable.
1 |
int[] arr; // Declaring an integer array |
Initialization: Assigns values to the array.
1 2 |
arr = new int[5]; // Initializing an array with 5 elements arr[0] = 10; // Assigning a value to the first element |
Alternatively, we can declare and initialize the array in a single line:
1 |
int[] arr = {10, 20, 30, 40, 50}; |
Basic Operations
Here are the common operations performed on arrays:
Insertion: Adding an element at a specific index (array size must be fixed in Java).
1 |
arr[2] = 25; // Inserting 25 at index 2 |
Deletion: Removing an element (though Java arrays do not support direct deletion, we can set an index to null
or shift elements manually).
1 |
arr[2] = 0; // Deleting by setting to a default value |
Traversal: Accessing array elements using loops.
1 2 3 |
for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } |
1 2 3 |
for(int num : numbers) { System.out.println(num); } |
Advantages & Disadvantages
Advantages | Disadvantages |
---|---|
Fixed size allows for efficient memory usage. | Fixed size means it cannot grow dynamically. |
Easy to implement and access elements using indices. | Inserting/deleting elements is cumbersome. |
Arrays can hold a large number of elements. | Limited to one data type (e.g., only integers, strings). |
Real-World Examples
- Database Tables: Each row can be represented as an array of values.
- Game Development: Storing the game board in a 2D array (like Tic-Tac-Toe).
- Image Processing: Pixels of an image can be represented using arrays where each element corresponds to a color value.