Data Structures
Java Arrays
Working with Arrays
Java arrays are fixed-length typed collections with indexing.
Introduction to Java Arrays
Java arrays are a fundamental data structure that provide a way to store a fixed number of elements of a specific type. Arrays are zero-indexed, meaning the first element is accessed with index 0. They offer efficient storage for data and allow quick access to elements by their index.
Each element in an array is of the same data type, and once an array is created, its size cannot be changed. Java provides several ways to manipulate arrays, including accessing, iterating over, and modifying elements.
Declaring and Initializing Arrays
In Java, arrays can be declared and initialized in several ways. Here's how you can declare an array:
- Declaration: Specify the type of elements the array will hold followed by square brackets.
- Initialization: Allocate memory for the array using the
new
keyword.
Let's look at an example:
In the example above, we declare an array of integers named numbers
and then allocate memory for 5 integers. Alternatively, you can declare and initialize an array in a single line:
This code snippet initializes the numbers
array with values 1 through 5. The array size is determined by the number of elements within the curly braces.
Accessing Array Elements
Elements in an array can be accessed using their index. The index is zero-based, so the first element is at index 0, the second element at index 1, and so on. Here's how you can access elements:
In this example, firstNumber
retrieves the first element of the array, and thirdNumber
retrieves the third element. Attempting to access an index outside the array bounds will result in an ArrayIndexOutOfBoundsException
.
Iterating Over Arrays
Iterating over arrays can be done using loops. The for
loop and enhanced for
loop (also known as the for-each
loop) are common ways to iterate through array elements:
The first loop iterates through the array using an index variable i
, while the enhanced for loop directly accesses each element in the array. Both loops will print all elements of the numbers
array.
Modifying Array Elements
Array elements can be modified by directly using their index. To change the value of an element, simply assign a new value to the desired index:
This code changes the third element of the numbers
array to 10. Modifying elements in this way is straightforward and efficient.
Multidimensional Arrays
Java also supports multidimensional arrays, which are arrays of arrays. The most common type is a two-dimensional array, often used to represent matrices or grids. Here's how you can declare a two-dimensional array:
This declares a 3x3 matrix. You can access elements using two indices:
Multidimensional arrays can be iterated using nested loops, providing a powerful way to manage complex data structures.
- Previous
- Annotations
- Next
- Lists