Java Arrays Tutorial with Code Examples

In Java, arrays are objects, and they provide a way to store a fixed-size sequential collection of elements. This tutorial will introduce the basics of using arrays in Java.

Declaring Arrays

You can declare an array by specifying its type followed by square brackets []. Here’s how you can declare an array of integers:

int[] myArray;

Instantiating Arrays

Once declared, you need to instantiate the array before using it:

myArray = new int[5]; // allocates memory for 5 integers

Combining declaration and instantiation:

int[] myArray = new int[5];

Initializing Arrays

Arrays can be initialized at the time of declaration:

int[] myArray = {1, 2, 3, 4, 5};

Or, individually:

myArray[0] = 1;
myArray[1] = 2;
// ... and so on

Accessing Array Elements

To access an array element, specify the index (starting from 0):

int secondValue = myArray[1]; // will assign 2 to secondValue

Array Length

To find out the length (or size) of an array:

int length = myArray.length; // length will be 5

Looping Through Arrays

The for loop is commonly used to iterate through arrays:

for(int i=0; i<myArray.length; i++) {
    System.out.println(myArray[i]);
}

You can also use the enhanced for loop:

for(int val : myArray) {
    System.out.println(val);
}

Multi-dimensional Arrays

Java supports multi-dimensional arrays. The most common type is the 2D array:

int[][] matrix = new int[3][3]; // a 3x3 matrix

Accessing elements:

matrix[0][0] = 1;

Initialization:

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

Iteration:

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

Common Mistakes with Java Arrays

  • Array Index Out of Bounds: Always ensure that the index you are trying to access exists. Java arrays are 0-based, so the last index is length - 1.

    myArray[5]; // Throws ArrayIndexOutOfBoundsException for an array of length 5
    
  • Not Initializing: Accessing an array before initializing will throw a NullPointerException.

    int[] array;
    System.out.println(array[0]); // Throws NullPointerException
    

Conclusion

Arrays are a crucial aspect of any programming language, and understanding their basic operations is essential for any Java developer. While this tutorial covers the basics, there’s much more to explore, especially when considering the various utilities provided by the Java framework.