Declaring and initializing arrays
There are different ways to declare and initialize arrays in Java. What you’ll need will depend a lot on the specific situation. So, let’s just start with the basics of declaring arrays.
Declaring arrays
To declare an array in Java, you need to specify the data type of the elements, followed by square brackets ([]
) and the array’s name. Take the following example:
int[] ages;
Here, int[]
is the data type of the array, and ages
is the name of the array. Right now, we can’t add any values to the array, because it hasn’t been initialized yet. This is different from initializing variables, which we have seen so far. Let’s see how to initialize arrays next.
Initializing arrays
After declaring an array, it needs to be initialized. We do this by specifying its size and allocating memory for the elements. We can use the new
keyword to do this, followed by the data type, and then specify the size of...