Skip to content

10. Arrays in Java

Table of Contents


10.1 What an Array Is

Arrays in Java are fixed-size, indexed, ordered collections of elements of the same type.

They are objects, even when the elements are primitives.

10.1.1 Declaring Arrays

You can declare an array in two ways:

int[] a;      // preferred modern syntax
int b[];      // legal, older style
String[] names;
Person[] people;

// [] can be before or after the name: all the following declarations are equivalent.

int[] x;
int [] x1;
int []x2;
int x3[];
int x5 [];

// MULTIPLE ARRAY DECLARATIONS

int[] arr1, arr2;   // Declares two arrays of int

// WARNING:
// Here arr1 is an int[] and arr2 is just an int (NOT an array!)
int arr1[], arr2;

Declaring does NOT create the array — it only creates a variable capable of referencing one.

10.1.2 Creating Arrays (Instantiation)

An array is created using new followed by the element type and the array length:

int[] numbers = new int[5];
String[] words = new String[3];

Key rules - The length must be non-negative and specified at creation time. - The length cannot be changed later. - The array length can be any int expression.

int size = 4;
double[] values = new double[size];
  • Illegal array creation examples:
// int length = -1;           
// int[] arr = new int[-1];   // Runtime: NegativeArraySizeException

// int[] arr = new int[2.5];  // Compile error: size must be int

10.1.3 Default Values in Arrays

Arrays (because they are objects) always receive default initialization:

Element Type Default Value
Numeric 0
boolean false
char '\u0000'
Reference types null
  • Example:
int[] nums = new int[3]; 
System.out.println(nums[0]); // 0

String[] s = new String[3];
System.out.println(s[0]);    // null

10.1.4 Accessing Elements

Elements are accessed using zero-based indexing:

int[] a = new int[3];
a[0] = 10;
a[1] = 20;
System.out.println(a[1]); // 20

Common exception
- ArrayIndexOutOfBoundsException (runtime)

// int[] x = new int[2];
// System.out.println(x[2]); // ❌ index 2 out of bounds

10.1.5 Array Initialization Shorthands

10.1.5.1 Anonymous Array Creation

int[] a = new int[] {1,2,3};

10.1.5.2 Short Syntax (Only at Declaration)

int[] b = {1,2,3};

The short syntax {1,2,3} can only be used at the point of declaration.

// int[] c;
// c = {1,2,3};  // ❌ does not compile

10.2 Multidimensional Arrays (Arrays of Arrays)

Java implements multi-dimensional arrays as arrays of arrays.

Declaration:

int[][] matrix;
String[][][] cube;

10.2.1 Creating a Rectangular Array

int[][] rect = new int[3][4]; // 3 rows, 4 columns each

10.2.2 Creating a Jagged (Irregular) Array

You can create rows with different lengths:

int[][] jagged = new int[3][];
jagged[0] = new int[2];
jagged[1] = new int[5];
jagged[2] = new int[1];

10.3 Array Length vs String Length

  • Arrays use .length (public final field).
  • Strings use .length() (method).

Tip

This is a classic trap: fields vs methods.

// int x = arr.length;   // OK
// int y = s.length;     // ❌ does not compile: missing ()
int yOk = s.length();

10.4 Array Reference Assignments

10.4.1 Assigning Compatible References

int[] a = {1,2,3};
int[] b = a; // both now point to the same array

Modifying one reference affects the other:

b[0] = 99;
System.out.println(a[0]); // 99

10.4.2 Incompatible Assignments (Compile-Time Errors)

// int[] x = new int[3];
// long[] y = x;     // ❌ incompatible types

Array references follow normal inheritance rules:

String[] s = new String[3];
Object[] o = s;      // OK: arrays are covariant

10.4.3 Covariance Runtime Danger: ArrayStoreException

Object[] objs = new String[3];
// objs[0] = Integer.valueOf(5); // ❌ ArrayStoreException at runtime

10.5 Comparing Arrays

== compares references (identity):

int[] a = {1,2};
int[] b = {1,2};
System.out.println(a == b); // false

equals() on arrays does not compare contents (it behaves like ==):

System.out.println(a.equals(b)); // false

To compare contents, use methods from java.util.Arrays:

Arrays.equals(a, b);         // shallow comparison
Arrays.deepEquals(o1, o2);   // deep comparison for nested arrays

10.6 Arrays Utility Methods

10.6.1 Arrays.toString()

System.out.println(Arrays.toString(new int[]{1,2,3})); // [1, 2, 3]

10.6.2 Arrays.deepToString() (for nested arrays)

System.out.println(Arrays.deepToString(new int[][] {{1,2},{3,4}}));
// [[1, 2], [3, 4]]

10.6.3 Arrays.sort()

int[] a = {4,1,3};
Arrays.sort(a); // [1, 3, 4]

Tip

  • Strings are sorted in natural (lexicographic) order.
  • Numbers sort before letters, and uppercase letters sort before lowercase letters (numbers < uppercase < lowercase).
  • For reference types, null is considered smaller than any non-null value.
String[] arr = {"AB", "ac", "Ba", "bA", "10", "99"};

Arrays.sort(arr);

System.out.println(Arrays.toString(arr));  // [10, 99, AB, Ba, ac, bA]

10.6.4 Arrays.binarySearch()

Requirements: the array must be sorted using the same ordering; otherwise the result is unpredictable.

int[] a = {1,3,5,7};
int idx = Arrays.binarySearch(a, 5); // returns 2

When the value is not found, binarySearch returns -(insertionPoint) - 1:

int pos = Arrays.binarySearch(a, 4); // returns -3
// Insertion point is index 2 → -(2) - 1 = -3

10.6.5 Arrays.compare()

The class Arrays offers an overloaded equals() that checks if two arrays contain the same elements (and have the same length):

System.out.println(Arrays.equals(new int[] {200}, new int[] {100}));        // false
System.out.println(Arrays.equals(new int[] {200}, new int[] {200}));        // true
System.out.println(Arrays.equals(new int[] {200}, new int[] {100, 200}));   // false

It also provides a compare() method with these rules:

  • If the result n < 0 → the first array is considered “smaller” than the second.
  • If the result n > 0 → the first array is considered “greater” than the second.
  • If the result n == 0 → the arrays are equal.

  • Examples:

int[] arr1 = new int[] {200, 300};
int[] arr2 = new int[] {200, 300, 400};
System.out.println(Arrays.compare(arr1, arr2));  // -1

int[] arr3 = new int[] {200, 300, 400};
int[] arr4 = new int[] {200, 300};
System.out.println(Arrays.compare(arr3, arr4));  // 1

String[] arr5 = new String[] {"200", "300", "aBB"};
String[] arr6 = new String[] {"200", "300", "ABB"};
System.out.println(Arrays.compare(arr5, arr6));     // Positive: "aBB" > "ABB"

String[] arr7 = new String[] {"200", "300", "ABB"};
String[] arr8 = new String[] {"200", "300", "aBB"};
System.out.println(Arrays.compare(arr7, arr8));     // Negative: "ABB" < "aBB"

String[] arr9 = null;
String[] arr10 = new String[] {"200", "300", "ABB"};
System.out.println(Arrays.compare(arr9, arr10));    // -1 (null considered smaller)

10.7 Enhanced for-loop with Arrays

for (int value : new int[]{1,2,3}) {
    System.out.println(value);
}

Rules - The right side must be an array or an Iterable. - The loop variable type must be compatible with the element type (no primitive widening here).

Common error:

// for (long v : new int[]{1,2}) {} // ❌ not allowed: int elements cannot be assigned to long in enhanced for-loop

10.8 Common Pitfalls

  • Accessing out of bounds → throws ArrayIndexOutOfBoundsException.

  • Using short array initializer incorrectly

// int[] x;
// x = {1,2}; // ❌ does not compile
  • Confusing .length and .length()
  • Forgetting that arrays are objects (they live on the heap and are referenced).

  • Mixing primitive arrays and wrapper arrays

// int[] p = new Integer[3]; // ❌ incompatible
  • Using binarySearch on unsorted arrays → unpredictable results.
  • Covariant array runtime exceptions (ArrayStoreException).

10.9 Summary

Arrays in Java are:

  • Objects (even if they hold primitives).
  • Fixed-size, indexed collections.
  • Always initialized with default values.
  • Type-safe, but subject to covariance rules (which can cause runtime exceptions if misused).