Arrays in Java
In Java, an array is a container object that holds a fixed number of values of a single type. Arrays are used to store multiple values in a single variable, rather than declaring separate variables for each value.
Here is an example of how to declare and initialize an array in Java:
int[] numbers = {1, 2, 3, 4, 5};
You can access the elements of an array using the index operator:
System.out.println(numbers[0]); // prints 1
System.out.println(numbers[1]); // prints 2
You 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]);
}
This will print all the elements of the numbers
array.
You can also declare an array and specify its size, and then initialize the elements of the array separately:
int[] numbers = new int[5];
numbers[0] = 1;
numbers[1] = 2;
In this example, we declare an array of integers called numbers
with a size of 5, and then assign values to each element of the array using the index operator ([]
).