Arrays are fundamental data structures in Java that store multiple values of the same type in a single variable.
Array Characteristics
- Fixed size: Once created, the size cannot be changed
- Indexed: Elements are accessed by their index (starting at 0)
- Homogeneous: All elements must be of the same type
- Contiguous memory: Elements are stored in consecutive memory locations
Declaring Arrays
// Different ways to declare arrays
int[] numbers1; // Preferred syntax
int numbers2[]; // Alternative syntax (less common)
Creating Arrays
// Creating arrays with size
int[] numbers = new int[5]; // Array of 5 integers (initialized to 0)
// Creating and initializing in one line
String[] names = {"Alice", "Bob", "Charlie"};
Accessing Array Elements
int[] numbers = {10, 20, 30, 40, 50};
// Accessing elements
System.out.println(numbers[0]); // Output: 10
System.out.println(numbers[2]); // Output: 30
// Modifying elements
numbers[1] = 25;
Array Length
int[] numbers = {10, 20, 30};
System.out.println(numbers.length); // Output: 3
Iterating Through Arrays
// Using for loop
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Using enhanced for loop (for-each)
for (int num : numbers) {
System.out.println(num);
}
Multidimensional Arrays
// 2D array (matrix)
int[][] matrix = new int[3][3]; // 3x3 matrix
// Initializing 2D array
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing elements
System.out.println(grid[1][2]); // Output: 6
Common Array Operations
// Sorting
Arrays.sort(numbers);
// Searching (array must be sorted)
int index = Arrays.binarySearch(numbers, 20);
// Copying
int[] copy = Arrays.copyOf(numbers, numbers.length);
// Filling
Arrays.fill(numbers, 0); // Sets all elements to 0
// Comparing
boolean equal = Arrays.equals(array1, array2);
Important Notes
- Array indices range from
0
tolength-1
- Accessing an invalid index throws
ArrayIndexOutOfBoundsException
- Arrays are objects in Java (even primitive arrays)
- The
length
property is final and cannot be changed
Array Limitations
- Fixed size (use
ArrayList
if you need dynamic sizing) - No built-in methods for common operations (use
Arrays
utility class) - Memory waste if array is larger than needed