Java Arrays

Arrays in Java — Declaration, Processing, Methods, Multi-Dimensional Arrays & Arrays of Objects

Prepared by Srikanth Mamillapalli

1. Java Arrays

Java provides a data structure called an array, which stores a fixed-size sequential collection of elements of the same type. This is also described as homogeneous data.

An array is useful for storing a collection of values. Instead of declaring individual variables such as number0, number1, ... number99, one array variable can represent them through indexed elements such as numbers[0], numbers[1], ... numbers[99].

Key idea: An array stores multiple values of the same data type under one array reference, and individual elements are accessed by index.
Java Arrays overview from source PDF

2. Declaring Array Variables

To use an array in a program, declare a variable that references the array and specify the type of array the variable can reference.

Syntax

dataType[] arrayRefVar;       // preferred way
dataType arrayRefVar[];       // works but not preferred

Example

double[] myList;              // preferred way
double myList[];              // works but not preferred
Recommendation: The source uses dataType[] arrayRefVar as the preferred declaration style.

3. Creating Arrays

You can create an array by using the new operator.

Syntax

arrayRefVar = new dataType[arraySize];

The statement performs two operations:

  1. Creates an array using new dataType[arraySize].
  2. Assigns the reference of the newly created array to arrayRefVar.

Array Indexing

Array indexes start at 0. For an array of size n, the valid indexes range from 0 through n - 1.

Array indexing and memory address diagrams from source PDF

4. Processing Arrays

When processing array elements, we often use either a for loop or a foreach loop, because all elements have the same type and the array size is known.

Using a for Loop

public class TestArray {
    public static void main(String[] args) {

        double[] myList = {1.9, 2.9, 3.4, 3.5};

        // Print all the array elements
        for (int i = 0; i < myList.length; i++) {
            System.out.println(myList[i] + " ");
        }

        // Summing all elements
        double total = 0;
        for (int i = 0; i < myList.length; i++) {
            total += myList[i];
        }
        System.out.println("Total is " + total);

        // Finding the largest element
        double max = myList[0];
        for (int i = 1; i < myList.length; i++) {
            if (myList[i] > max)
                max = myList[i];
        }
        System.out.println("Max is " + max);
    }
}

This example demonstrates three common array operations: printing every element, calculating the total, and finding the largest element.

Processing arrays using for loop from source PDF

5. The foreach Loop

The enhanced for loop provides a simple way to visit every element without explicitly managing an index.

Example

public class TestArray {
    public static void main(String[] args) {

        double[] myList = {1.9, 2.9, 3.4, 3.5};

        // Print all the array elements
        for (double element : myList) {
            System.out.println(element);
        }
    }
}
Syntax pattern: for (Type element : array) assigns each array element to the loop variable one at a time.

6. Passing Arrays to Methods

Arrays can be passed to methods just like other reference-type values.

Example

public static void printArray(int[] array) {
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i] + " ");
    }
}

The method receives an int[] parameter and can access its elements using the index.

Passing arrays to methods from source PDF

7. Returning an Array from a Method

A method may also return an array. The source provides an example that returns the reverse of another array.

Example

public static int[] reverse(int[] list) {
    int[] result = new int[list.length];

    for (int i = 0, j = result.length - 1;
         i < list.length;
         i++, j--) {
        result[j] = list[i];
    }

    return result;
}
Return type: The method is declared with int[], meaning it returns a reference to an integer array.
Returning an array from a method and one-dimensional array diagram

8. Types of Arrays in Java

The source identifies two broad types of arrays:

1. Single-Dimensional Array

An array with only one subscript or one dimension. It is a list of variables of the same data type.

2. Multi-Dimensional Array

An array in which elements can themselves be organized into additional dimensions, such as 2D, 3D and beyond.

Single-Dimensional Array

int[] a = {10, 20, 30, 40, 50};

Conceptually, a one-dimensional array looks like:

a[0]   a[1]   a[2]   ...   a[n-1]

Multi-Dimensional Array

Sometimes a program needs an array within an array. A common example is a two-dimensional matrix.

9. Multi-Dimensional Arrays

The source illustrates a two-dimensional array using rows and columns.

Declaration and Initialization

int marks[][] = {
    {77,85,68,99,87},
    {98,56,79,90,92},
    {78,88,56,70,99}
};

OR

int marks[][] = new int[3][5];

Two-Dimensional Matrix Example

public class Demo {
    public static void main (String[] args) {

        // declaring and initializing arrays
        int arr1[][] = {{1,2,3},{4,5,6},{7,8,9}};
        int arr2[][] = {{2,2,2},{2,2,2},{2,2,2}};

        // Printing Array1 in matrix format
        System.out.println("Array1 -");
        for(int i=0;i<3;i++) {
            for(int j=0;j<3;j++) {
                System.out.print(arr1[i][j] + " ");
            }
            System.out.println();
        }

        // Printing Array2 in matrix format
        System.out.println("Array2 -");
        for(int i=0;i<3;i++) {
            for(int j=0;j<3;j++) {
                System.out.print(arr2[i][j] + " ");
            }
            System.out.println();
        }

        int arr3[][] = new int[3][3];
    }
}
Two-dimensional array and matrix code from source PDF

10. Matrix Multiplication

The source uses matrix multiplication as a well-known example of a 2D array. Two 3×3 arrays are multiplied and the result is stored in a third 3×3 array.

Core Logic

// Multiplying arr1 and arr2, storing results in arr3
System.out.println("Multiplication of Array1 and Array2 - ");

for(int i=0;i<arr1.length;i++) {
    for(int j=0;j<arr2.length;j++) {
        arr3[i][j] = 0;

        for(int k=0;k<arr3.length;k++) {
            arr3[i][j] += arr1[i][k] * arr2[k][j];
        }

        System.out.print(arr3[i][j] + " ");
    }
    System.out.println();
}

Output

Array1 -
1 2 3
4 5 6
7 8 9

Array2 -
2 2 2
2 2 2
2 2 2

Multiplication of Array1 and Array2 -
12 12 12
30 30 30
48 48 48
Concept: The result array uses the same 3×3 dimensions and each result element is calculated from the corresponding row and column values.
Matrix multiplication code and output from source PDF

11. Arrays of Objects

An array of objects is an array that stores references to objects. The array does not contain the complete object instances directly; its elements are object reference variables.

Syntax

Student studentObj[] = new Student[3];

This creates an array of length 3 containing three Student references. Each reference can then be initialized using new.

Example

class Student {
    Student(int id, String name) {
        System.out.println("Student ID is " + id + " and name is " + name);
    }
}

public class Test {
    public static void main (String[] args) {

        // declaring an array of Object
        Student obj[] = new Student[3];

        obj[0] = new Student(1,"Bharat");
        obj[1] = new Student(5,"Vivaan");
        obj[2] = new Student(6,"Smith");
    }
}

Output

Student ID is 1 and name is Bharat
Student ID is 5 and name is Vivaan
Student ID is 6 and name is Smith

The source explains that the array first creates three reference variables, obj[0], obj[1] and obj[2]. Each reference is then initialized with a separate new Student(...) object.

Array of objects example and advantages from source PDF

12. Advantages and Disadvantages of Arrays in Java

Advantages

  • Array elements can be accessed randomly using their index.
  • Many values can be stored at a time.
  • It is easier to create and work with multi-dimensional arrays.

Disadvantages

  • Java arrays do not have built-in remove or add methods.
  • The size must be specified, which can result in memory wastage when the required size changes.
  • The source recommends ArrayList when dynamic sizing is required.
  • Arrays in Java are strongly typed.
Advantages and disadvantages of arrays from source PDF

13. Conclusion & Quick Revision

  • An array in Java is a non-primitive data type used to store multiple values of the same data type.
  • Array elements are accessed using indexes from 0 to length - 1.
  • A for loop and enhanced for-each loop can be used to traverse array elements.
  • Java supports single-dimensional and multi-dimensional arrays, including 2D, 3D and nD forms.
  • Arrays can contain primitive values as well as references to objects.
  • Arrays can be passed to methods and returned from methods.
  • An array without a named variable is commonly called an anonymous array for immediate use.
  • The source also mentions using clone() for duplicating arrays.

Frequently Asked Questions

QuestionAnswer
What is an array?A homogeneous non-primitive data type used to store multiple same-type values in one variable.
Are arrays reference types in Java?Yes. An array is a reference type and is treated as a reference to an array object.
Are arrays primitive data types?No. Arrays are non-primitive/reference types, although they can hold primitive values.
Can you increase the size of an array?No. Once an array is created, its length cannot be changed at runtime. A new array or a dynamic collection such as ArrayList is needed.
Arrays conclusion and FAQ from source PDF