The array is a type of data structure in Java that stores a fixed-size collection of elements of the same type in order. An array is a place to store a group of data, but it is often easier to think of it as a group of variables of the same type. Instead of declaring individual variables like number0, number1,..., and number99, you declare one array variable like numbers and use numbers[0], numbers[1],..., and numbers[99] to represent individual variables. This tutorial shows you how to declare array variables, make arrays, and use indexed variables to work with arrays.
Declaring Array Variables
dataType[ ] arrayRefVar; // preferred way.
or
dataType arrayRefVar[ ]; // works but not preferred way.
Example
The following code snippets are examples of this syntax −
double[ ] myList; // preferred way.
or
double myList[ ]; // works but not preferred way.
Creating Arrays
You can create an array by using the new operator with the following syntax −
Syntax
arrayRefVar = new dataType[arraySize];
The above statement does two things −
- It creates an array using new dataType[arraySize].
- It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below −
dataType[ ] arrayRefVar = new dataType[arraySize];
Alternatively, you can create arrays as follows −
dataType[ ] arrayRefVar = {value0, value1, ..., valuek};
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList −
double[ ] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.

Processing Arrays
Because all the elements in an array are the same type and the size of the array is known, we often use either the for loop or the foreach loop to process them.

The foreach Loops
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Example
The following code displays all the elements in the array myList −
