Introduction to Java Arrays
Arrays in Java are used to store multiple values of the same data type under a single variable name. They provide a convenient way to work with collections of data and are widely used in programming.
Declaring Arrays
To declare an array in Java, you specify the data type of the elements followed by square brackets []
and then the name of the array variable.
Example:
int[] numbers; // Declares an array of integers
Creating Arrays
After declaring an array variable, you need to create the array itself using the new
keyword followed by the data type and the number of elements in the array.
Example:
numbers = new int[5]; // Creates an array of 5 integers
Alternatively, you can combine the declaration and creation of an array in a single line:
int[] numbers = new int[5]; // Declares and creates an array of 5 integers
Initializing Arrays
You can initialize the elements of an array during declaration or later in the program.
Initializing During Declaration
int[] numbers = {10, 20, 30, 40, 50}; // Initializes array elements during declaration
Initializing Later
numbers[0] = 10; numbers[1] = 20; numbers[2] = 30; numbers[3] = 40; numbers[4] = 50;
Accessing Array Elements
Array elements are accessed using the array name followed by the index of the element within square brackets.
Example:
int firstElement = numbers[0]; // Accesses the first element of the array
Array Length
You can determine the length of an array using the length
property.
Example:
int length = numbers.length; // Retrieves the length of the array
Iterating Over Arrays
Arrays can be iterated using loops such as for
or foreach
.
Using a For Loop
for (int i = 0; i < numbers.length; i++) { System.out.println(numbers[i]); }
Using a For-Each Loop
for (int number : numbers) { System.out.println(number);
}
Multidimensional Arrays
Java supports multidimensional arrays, which are arrays of arrays.
Example:
int[][] matrix = new int[3][3]; // Declares a 2D array of integers
Arrays vs. ArrayLists
Java arrays have fixed lengths and are less flexible compared to ArrayLists, which can dynamically resize. However, arrays are more efficient in terms of memory and performance.
Java arrays are powerful constructs that allow you to store and manipulate collections of data efficiently. Understanding how to declare, create, initialize, access, and iterate over arrays is essential for writing effective Java programs.