Arrays are a data structure that allows us to store a fixed-size sequential collection of elements of the same type.
To declare an array in Java, we use the following syntax:
type[] arrayName;
For example, if we want to create an array of integers, we can write:
int[] numbers;
We can also initialize an array when we declare it by including the size and the values within curly braces:
int[] numbers = {1, 2, 3, 4, 5};
We can also create an array with a specific size and then add elements to it later:
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
// and so on...
One thing to keep in mind is that in Java, arrays are zero-indexed, meaning the first element is at index 0, the second element is at index 1, and so on.
We can access the elements of an array using the square bracket notation:
int firstElement = numbers[0];
We can also use a loop to iterate over the elements of an array:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
That’s just a quick overview of arrays in Java. There’s a lot more you can do with them, such as sorting, searching, and so on, but this should give you a good foundation to start from.