Arrays in Java

โšก Smart Summary

Arrays in Java are fixed-size, index-based containers that store elements of one data type in contiguous memory, giving constant-time access, built-in bounds checking, and a length field that make them the foundation for most standard-library collections.

  • ๐Ÿ“ฆ Fixed size: An array holds a set number of elements of a single type.
  • ๐Ÿ”ข Zero-based index: Elements run from 0 to length minus one.
  • ๐Ÿงฉ Two types: Java has single-dimensional and multidimensional arrays.
  • ๐Ÿ› ๏ธ Three steps: Every array is declared, constructed with new, and initialised.
  • ๐Ÿ›ก๏ธ Bounds checking: The JVM throws ArrayIndexOutOfBoundsException past the last slot.
  • โ†ฉ๏ธ By reference: Element changes made inside a method persist for the caller.
  • ๐Ÿ“ Length field: Every array exposes length for safe iteration.

Arrays in Java

What Is a Java Array?

A Java array is a fixed-size structure that stores elements of one data type in contiguous memory. Each element is reached by a zero-based index, so the first sits at 0 and the last at length - 1. Arrays inherit from Object and implement Serializable and Cloneable, and can hold primitives or object references.

Arrays replace long runs of numbered variables. Consider six independent integers:

x0 = 0;
x1 = 1;
x2 = 2;
x3 = 3;
x4 = 4;
x5 = 5;

The same six values live in a single array of length six:

x[0] = 0;
x[1] = 1;
x[2] = 2;
x[3] = 3;
x[4] = 4;
x[5] = 5;

A loop variable can drive the index in brackets, so three lines process every element instead of six copies:

for (int count = 0; count < 5; count++) {
    System.out.println(x[count]);
}

Types of Array in Java

Java arrays come in two shapes:

  1. Single-dimensional array: a flat list of elements.
  2. Multidimensional array: an array of arrays, used for grids and matrices.

Array Variables: Declare, Construct, and Initialise

Using an array is a three-step process: declare, construct with new, then initialise.

1) Declare the Array

Syntax:

<elementType>[] <arrayName>;

or (the older C-style form, still valid):

<elementType> <arrayName>[];

Example:

int[] intArray;   // canonical form: brackets on the type
int intArray2[];  // legacy C-style form, discouraged in new code

2) Construct the Array

Syntax:

arrayName = new dataType[size];

Example:

intArray = new int[10]; // defines that intArray will store 10 integer values

Declaration and construction combined:

int[] intArray = new int[10];

3) Initialise the Array

intArray[0] = 1; // assigns 1 to the first element (index 0)
intArray[1] = 2; // assigns 2 to the second element (index 1)

Declare and initialise in one step using an array literal:

int[] intArray = {1, 2, 3, 4};
// initialises an integer array of length 4 where the first element is 1,
// the second element is 2, and so on.

First Array Program in Java

Step 1) Copy the following code into an editor:

class ArrayDemo {
    public static void main(String args[]) {
        int array[] = new int[7];

        for (int count = 0; count < 7; count++) {
            array[count] = count + 1;
        }

        for (int count = 0; count < 7; count++) {
            System.out.println("array[" + count + "] = " + array[count]);
        }

        // System.out.println("Length of Array  =  " + array.length);
        // array[8] = 10;
    }
}

Step 2) Save, compile, and run the code. Observe the output.

Expected Output:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5
array[5] = 6
array[6] = 7

Step 3) If x is an array reference, x.length returns its slot count. Uncomment the first commented line and re-run:

Length of Array  =  7

Step 4) Unlike C, Java bounds-checks every array access. Uncomment the second commented line and re-run:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 8
        at ArrayDemo.main(ArrayDemo.java:11)
Command exited with non-zero status 1

Step 5) The JVM throws ArrayIndexOutOfBoundsException. In C the same access would return garbage from adjacent memory instead of failing.

Java Array: Pass by Reference

Arrays are passed to methods by reference. The method receives a copy of the reference, so element changes made inside the method are visible to the caller.

Example: arrays are passed by reference.

Step 1) Copy the following code into an editor:

class ArrayDemo {
    public static void passByReference(String a[]) {
        a[0] = "Changed";
    }

    public static void main(String args[]) {
        String[] b = {"Apple", "Mango", "Orange"};
        System.out.println("Before Function Call    " + b[0]);
        ArrayDemo.passByReference(b);
        System.out.println("After Function Call    " + b[0]);
    }
}

Step 2) Save, compile, and run the code. Observe the output.

Expected Output:

Before Function Call    Apple
After Function Call    Changed

Multidimensional Arrays in Java

Multidimensional arrays are arrays of arrays. Add another set of square brackets for each dimension. To create a 2-D integer grid with four rows and five columns:

int[][] twoD = new int[4][5];

You only need to size the first (leftmost) dimension up front. The remaining dimensions can be allocated separately, and each row can have its own length, making Java 2-D arrays true jagged arrays.

Example:

public class Guru99 {
    public static void main(String[] args) {
        // Create a 2-dimensional array with 4 rows and 4 columns.
        int[][] twoD = new int[4][4];

        // Assign three elements to it.
        twoD[0][0] = 1;
        twoD[1][1] = 2;
        twoD[3][2] = 3;

        System.out.print(twoD[0][0] + " ");
    }
}

Expected Output:

1

FAQs

A Java array is a fixed-size container that stores elements of one data type. Each element is accessed by a zero-based index, and every array exposes a length field with the slot count.

Declare with int[] arr, construct with new int[size], then assign by index. To do all three in one line, use a literal such as int[] arr = {1, 2, 3, 4}.

Java supports single-dimensional and multidimensional arrays. A single-dimensional array is a flat list, and a multidimensional array is an array of arrays used for tables, grids, and matrices.

Use the length field, for example arr.length. It returns the slot count and works for any array type. Unlike String, arrays expose length as a field, not a method call.

The JVM bounds-checks every array access. Reading or writing an index below zero or at or above length throws ArrayIndexOutOfBoundsException, preventing the memory corruption bugs that plague C and C++.

Java passes arguments by value, but for arrays that value is a copy of the reference. The method acts on the same underlying array, so element changes inside the method are visible to the caller.

Machine learning code assistants recognise the declare-construct-initialise pattern and complete literals or loops. They also flag common off-by-one errors that would throw ArrayIndexOutOfBoundsException at runtime.

Yes. GitHub Copilot scaffolds array declarations, loops, Arrays.sort calls, and 2-D matrix walks from a plain-language comment. Review the generated bounds before running against production data.

Summarize this post with: