Java Arrays
In Java, an array is a data structure that stores a fixed-size sequence of elements of the same type. Each element in the array is identified by its index, which is a non-negative integer that specifies the position of the element in the array.
Here's an example of how to declare and initialize an array of integers in Java:
int[] numbers = {1, 2, 3, 4, 5};
This creates an array of integers with five elements, and initializes it with the values 1, 2, 3, 4, and 5.
You can access the elements of an array using the square bracket notation, like this:
int firstNumber = numbers[0]; // Gets the first element of the array (1) int lastNumber = numbers[numbers.length - 1]; // Gets the last element of the array (5)
Note that the index of the first element in the array is 0, and the index of the last element is array.length - 1
, where array
is the name of the array.
You can also create an array without initializing its elements, like this:
int[] numbers = new int[5];
This creates an array of integers with five elements, but doesn't initialize them. In this case, all the elements of the array will be set to 0 by default.
Finally, you can use the Arrays
class in the java.util
package to perform various operations on arrays, such as sorting, searching, and filling:
int[] numbers = {5, 3, 1, 4, 2}; Arrays.sort(numbers); // Sorts the array in ascending order int index = Arrays.binarySearch(numbers, 3); // Searches for the element 3 in the array Arrays.fill(numbers, 0); // Fills the array with zeros