An array is a special construct whose purpose is to store multiple values in a single variable, instead of declaring separate variables for each value. Moreover, in Java, an array is a collection of similar type of elements which has contiguous memory location. Unlike the Arraylist Class, the primitive array (lowercase “a”) holds a fixed number of values. In this programming tutorial, developers will learn how to work with arrays in Java. Specifically, we will discuss how to declare, initialize, and access array elements with the help of plenty of code examples.
You can learn more about the Arraylist Class in our guide: Overview of the Java Arraylist Class.
How to Declare an Array in Java
The syntax to declare an array in Java is similar to that of any data type, except we add square brackets ([]) after the data type or variable name, as shown in the code example below:
dataType[] arrayName; OR dataType arrayName[];
Note that arrays may contain any dataType from primitive types like int, char, double, byte, and even Java objects. The only caveat is that they must all be of the same type.
Here are some examples of how to declare arrays in Java:
int intArray[]; int[] intArray2; byte byteArray[]; short shortsArray[]; boolean booleanArray[]; long longArray[]; float[] floatArray; double[] doubleArray; char[] charArray; MyClass myClassArray[]; Object[] arrO, // array of Object Collection[] arrC; // array of Collection
Instantiating an Array in Java
It is worth noting that when an array is declared, only a reference of an array is created. As such, no actual array exists yet. This reference merely tells the compiler that the array variable will hold an array of a given type. To associate the array variable with an actual, physical array of values, developers must allocate one using the new keyword and assign it to the array as follows;
arrayName = new type[size];
The size parameter specifies how many discreet values the array will contain so that the Java Virtual Machine (JVM) can allocate the necessary memory. Each slot in the array is referred to as an element.
Here are the Java statements used to declare and allocate 10 elements to an int array:
int intArray[]; // declaring array intArray = new int[10]; // allocating memory to array
Both the variable declaration and memory allocation statements may be combined:
int[] intArray = new int[10];
You might be wondering what is inside of the ten slots that we just allocated? In the case of arrays, Java follows the same conventions as for variables that contain a single value. Hence, the elements in the array allocated by new will automatically be initialized to 0 (for numeric types), false (for boolean), or null (for reference types).
Read: Top Online Courses to Learn Java
How to Populate an Array in Java
Since we probably do not want our arrays to have default values, we will have to add our own values to any array we create. There are a few ways to do that; the easiest is to create an array literal, which we can do with the following code:
int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
This method is ideal for situations where the size of the array (and variables of the array) are already known. Note that the size does not have to be specified, as the JVM will allocate whatever size is required to hold the given values.
Using the more recent Java versions, we can also do away with the new int[] portion of our code and simply use:
int[] intArray = { 1,2,3,4,5,6,7,8,9,10 };
How to Access Java Array Elements
Developers can also initialize each array element individually, but in order to do that, we need to know how to access a specific element. Array elements can be accessed using their index number. Java arrays are zero based, meaning that the first element has a zero (0) index. Here is the syntax for accessing elements of an array in Java:
array[index]
With this in mind, we could initialize our intArray as follows:
intArray[0] = 12; intArray[1] = 4; intArray[2] = 5; intArray[3] = 9; //etc...
Programmers can employ the same syntax to read element values:
System.out.println("First Element: " + intArray[0]); System.out.println("Second Element: " + intArray[1]); System.out.println("Third Element: " + intArray[2]); /* prints: First Element: 12 Second Element: 4 Third Element: 5 */
Traversing Java Array Elements Using Loops
The for loop is tailor-made for iterating over arrays, since its counter variable can be readily utilized to access the current array element. The only catch is that developers have to be careful not to continue past the end of the array. Otherwise, we will get a java.lang.
public class Main { public static void main(String[] args) { int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 }; for (int i = 0; i < intArray.length; i++) { System.out.println("intArray[" + i + "]: " + intArray[i]); } } }
Executing the above code outputs the following results:
You can learn more about loops in our tutorial: Introduction to the Java For Loop.
Traversing Java Arrays with the For-each Loop
Java version 5 introduced an enhanced for statement known as a for-each loop. This kind of loop allows programmers to iterate over arrays or lists without having to calculate the index of each element. The enhanced for has the following format and syntax:
for (<loop variable> : <iterable>) { // do your stuff here }
Here is our previous loop example, refactored as a for-each loop:
for (int elt : intArray) { System.out.println("intArray[" + i + "]: " + elt); }
Multidimensional Arrays
Array elements may themselves hold a reference to other arrays, creating multidimentional arrays. In Java, a multidimensional array is declared by appending one set of square brackets ([]) per dimension, like so:
int[][] intArray2D = new int[10][15]; //a 2D array int[][][] intArray3D = new int[10][20][20]; //a 3D array
Here is a program that declares and initializes a two-dimentional array before printing its contents to the console:
public class MultiDimensionalArrayExample { public static void main(String args[]) { int arr[][] = { { 4, 7, 3 }, { 5, 9, 1 }, { 10, 4, 2 } }; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
We can see the full program and output below:
Final Thoughts On Java Arrays
In this programming tutorial, we learned how to declare and initialize Java arrays, as well as how to access their elements. We also discussed how to create multidimensional arrays and learned to traverse arrays use the for and for-each loops. Arrays are the ideal choice for holding a fixed number of values of the same type. However, if you need dynamic sizing, consider going with an ArrayList instead.
Looking to learn more about Java arrays? Check out these tutorials: