We’ve talked about arrays, now let’s look at how they are created in Java.
In a general form, you can find something like below:
type var-name[];
OR
type[] var-name;
Obviously type would be something like int, float, or even a class name as you can have an array of objects.
Declaring an Array
This means that the following are ways to legitimately create an array of integers in Java.
// both are valid declarations
int intArray[];
or int[] intArray;
// creating an array of objects
MyClass myClassArray[];
These of course only define the name. They do not create memory, as the size of the array is not given at this time. So we need to create a new line of code to create the actual array, rather then just saying it will exist.
int intArray[]; //declaring array
intArray = new int[10]; // allocating memory to array with 10 elements
Of course, you can combine these into a single line of code:
int intArray[] = new int[10]; // combining two lines of code into one
The new keyword is used anytime you need to define memory space for an element. This allows the elements to be initialized. The elements in the array are automatically initialized to zero (for numeric types), false (for boolean), or null (for reference types) as is standard for Java.
Initializing an Array
If you want, you can initialize an array with literal values as well.
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal
Note that you do not need to specify the number of elements if you are going to initialize it with literal values.
Accessing the Array
Arrays in Java are zero (0) based, just like C/C++. Using a for loop is a common way to go through an array in Java.
Unlike C however, we have a property for the array which allows us to know the length. So we don’t have to keep track of it with constants, external variables, etc. Most people find this easier to work with.
// accessing the elements of the specified array
for (int i = 0; i < intArray.length; i++)
{
System.out.println("Element at index " + i + " : "+ intArray[i]);
}
Arrays in Java was originally found on Access 2 Learn