Arrays in Java are a fundamental data structure that allows you to store multiple values of the same type in a single variable. Arrays are indexed, meaning each element of an array is associated with a unique index that allows for direct access. Let’s delve into arrays with examples and detailed comments.
Declaring Arrays
You can declare an array in Java by specifying the data type of its elements, followed by square brackets.
Example:
1 2 |
int[] numbers; // Declaration of an array that will store integers. String[] names; // Declaration of an array that will store strings. |
Initializing Arrays
Arrays can be initialized when they are declared or after declaration.
Example:
1 2 |
int[] numbers = {10, 20, 30, 40, 50}; // Declaration and initialization. String[] names = new String[]{"John", "Jane", "Doe"}; // Another form of declaration and initialization. |
Accessing Array Elements
Array elements are accessed by their index. Note that array indices start at 0.
Example:
1 2 |
System.out.println(numbers[0]); // Accesses the first element of the numbers array. Output: 10 System.out.println(names[2]); // Accesses the third element of the names array. Output: Doe |
Modifying Array Elements
You can modify an element of an array by accessing it by its index and assigning a new value.
Example:
1 2 |
numbers[1] = 25; // Modifies the second element of the numbers array. System.out.println(numbers[1]); // Output: 25 |
Iterating Over Arrays
You can iterate over array elements using a for
loop or an enhanced for
loop (for-each loop).
Using a for loop:
1 2 3 |
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); } |
Using a for-each loop:
1 2 3 |
for (String name : names) { System.out.println(name); } |
Multidimensional Arrays
Java supports multidimensional arrays, which are arrays of arrays.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; // Accessing elements System.out.println(matrix[0][0]); // Output: 1 System.out.println(matrix[2][2]); // Output: 9 // Iterating over a multidimensional array 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(); // For new line after each row } // Output: // 1 2 3 // 4 5 6 // 7 8 9 |
Array Length
You can find the length of an array using the length
property.
Example:
1 |
System.out.println(numbers.length); // Output: 5 |
Arrays in Java are a versatile data structure used to store collections of data. They play a crucial role in various programming scenarios, from simple data storage to complex algorithms. Understanding how to declare, initialize, access, and iterate over arrays is fundamental for any Java programmer