Arrays in Java

Master array creation, initialization, multi-dimensional arrays, array operations, and array methods for the OCP 21 exam.

Table of Contents

1. Array Basics

An array is a container object that holds a fixed number of values of a single type. Arrays are objects in Java and are stored on the heap.

1.1 Array Characteristics

  • Fixed Size: Size is determined at creation and cannot be changed
  • Homogeneous: All elements must be of the same type
  • Indexed: Elements accessed by index (0-based)
  • Object: Arrays are objects, even for primitive types
  • Length Property: length field (not method) gives array size

1.2 Array Types

  • Primitive arrays: int[] , double[] , char[] , etc.
  • Object arrays: String[] , Object[] , Person[] , etc.

2. Array Creation

Arrays can be created using several syntax variations.

2.1 Declaration Syntax

Example:
// Different declaration styles (all equivalent) int[] numbers1;
// Preferred style int numbers2[];
// C-style (valid but not recommended) // Primitive arrays int[] intArray;
double[] doubleArray;
char[] charArray;
boolean[] booleanArray;
// Object arrays String[] stringArray;
Object[] objectArray;
Person[] personArray;

2.2 Creating Arrays

Example:
// Create array with size int[] numbers = new int[5];
// Array of 5 integers (all initialized to 0) // Create and initialize in one statement int[] numbers2 = new int[]{1, 2, 3, 4, 5};
int[] numbers3 = {1, 2, 3, 4, 5};
// Shorthand (only in declaration) // Object arrays String[] names = new String[3];
// All elements are null String[] names2 = {"Alice","Bob","Charlie"};
// Cannot use shorthand after declaration int[] arr;
// arr = {1, 2, 3};
// Compilation error arr = new int[]{1, 2, 3};
// Correct

3. Array Initialization

3.1 Default Values

When arrays are created, elements are initialized to default values:

Type Default Value
byte, short, int, long 0
float, double 0.0
char '\u0000' (null character)
boolean false
Object references null
Example:
// Default initialization int[] numbers = new int[5];
// numbers = [0, 0, 0, 0, 0] double[] values = new double[3];
// values = [0.0, 0.0, 0.0] boolean[] flags = new boolean[2];
// flags = [false, false] String[] names = new String[3];
// names = [null, null, null] // Explicit initialization int[] arr = {10, 20, 30};
// arr = [10, 20,
30]

4. Accessing Array Elements

Array elements are accessed using index notation. Indices start at 0 and go up to length-1.

4.1 Reading and Writing Elements

Example:
int[] numbers = {10, 20, 30, 40, 50};
// Reading elements int first = numbers[0];
// 10 int second = numbers[1];
// 20 int last = numbers[4];
// 50 // Writing elements numbers[0] = 100;
// Modify first element numbers[2] = 300;
// Modify third element // Array length int length = numbers.length;
// 5 (not a method, it's a field) // Iterating through array for (int i = 0;

i < numbers.length;
i++) {
    System.out.println(numbers[i]);
} // Enhanced for loop for (int num : numbers) {

    System.out.println(num);
}

4.2 ArrayIndexOutOfBoundsException

Common Error:
int[] arr = {1, 2, 3};
// WRONG: Index out of bounds // int value = arr[3];
// ArrayIndexOutOfBoundsException (valid indices: 0-2) // int value = arr[-1];
// ArrayIndexOutOfBoundsException // CORRECT: Valid indices int value = arr[0];
// 1 int value2 = arr[2];
// 3 (last valid index) // Always check bounds if (index >= 0 && index < arr.length) {
    int value = arr[index];
}

5. Multi-Dimensional Arrays

Java supports multi-dimensional arrays (arrays of arrays).

5.1 Two-Dimensional Arrays

Example:
// 2D array declaration int[][] matrix;
// Create 2D array int[][] matrix1 = new int[3][4];
// 3 rows, 4 columns // Initialize 2D array int[][] matrix2 = {
    {1, 2, 3}, {4, 5, 6}, {7, 8, 9}
};
// Accessing elements int value = matrix2[0][0];
// 1 (first row, first column) int value2 = matrix2[1][2];
// 6 (second row, third column) // Iterating 2D array for (int i = 0;
i < matrix2.length;
i++) {
    for (int j = 0;
    j < matrix2[i].length;
    j++) {
        System.out.print(matrix2[i][j] +"");
    }
System.out.println();
} // Enhanced for loop for (int[] row : matrix2) {
for (int value : row) {
    System.out.print(value +"");
}
System.out.println();
}

5.2 Jagged Arrays

Jagged arrays are arrays where each row can have different lengths.

Example:
// Jagged array (ragged array) int[][] jagged = new int[3][];
jagged[0] = new int[2];
// First row has 2 elements jagged[1] = new int[4];
// Second row has 4 elements jagged[2] = new int[3];
// Third row has 3 elements // Initialize jagged array int[][] jagged2 = {
    {1, 2}, {3, 4, 5, 6}, {7, 8, 9}
};
// Accessing jagged array int val = jagged2[0][1];
// 2 int val2 = jagged2[1][3];
// 6 // Iterating jagged array for (int i = 0;
i < jagged2.length;
i++) {
    for (int j = 0;
    j < jagged2[i].length;
    j++) {
        System.out.print(jagged2[i][j] +"");
    }
System.out.println();
}

5.3 Three-Dimensional Arrays

Example:
// 3D array int[][][] cube = new int[3][4][5];
// 3x4x5 array // Initialize 3D array int[][][] cube2 = {
    {{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}
};
// Accessing 3D array int value = cube2[0][1][0];
// 3

6. Array Operations

6.1 Common Operations

Example:
int[] numbers = {5, 2, 8, 1, 9};
// Finding maximum int max = numbers[0];
for (int i = 1;
i < numbers.length;
i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
} // Finding minimum int min = numbers[0];
for (int num : numbers) {
    if (num < min) {
        min = num;
    }
} // Sum of elements int sum = 0;
for (int num : numbers) {
    sum += num;
} // Searching for element int target = 8;
boolean found = false;
for (int num : numbers) {
    if (num == target) {
        found = true;
        break;
    }
} // Copying array int[] copy = new int[numbers.length];
for (int i = 0;
i < numbers.length;
i++) {
    copy[i] = numbers[i];
} // Or using System.arraycopy() int[] copy2 = new int[numbers.length];
System.arraycopy(numbers, 0, copy2, 0, numbers.length);

6.2 Array Comparison

Example:
int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
int[] arr3 = arr1;
// Reference comparison System.out.println(arr1 == arr2);
// false (different objects) System.out.println(arr1 == arr3);
// true (same reference) // Content comparison (manual) boolean equal = true;
if (arr1.length != arr2.length) {
    equal = false;
}
else {
    for (int i = 0;
    i < arr1.length;
    i++) {
        if (arr1[i] != arr2[i]) {
            equal = false;
            break;
        }
} } // Using Arrays.equals() import java.util.Arrays;
boolean isEqual = Arrays.equals(arr1, arr2);
// true

7. Array Methods

The java.util.Arrays class provides static methods for array operations.

7.1 Common Arrays Methods

Example:
import java.util.Arrays;
int[] numbers = {5, 2, 8, 1, 9};
// Sorting Arrays.sort(numbers);
// [1, 2, 5, 8, 9] (modifies original) // Binary search (array must be sorted) int index = Arrays.binarySearch(numbers, 5);
// Returns index // Filling array int[] arr = new int[5];
Arrays.fill(arr, 10);
// [10, 10, 10, 10, 10] // Copying array int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] copy2 = Arrays.copyOfRange(numbers, 1, 4);
// Copy from index 1 to 3 // Converting to string String str = Arrays.toString(numbers);
//"[1, 2, 5, 8, 9]" // Deep toString for multi-dimensional arrays int[][] matrix = {{1, 2}, {3, 4}};
String str2 = Arrays.deepToString(matrix);
//"[[1, 2], [3, 4]]" // Comparing arrays int[] arr1 = {1, 2, 3};
int[] arr2 = {1, 2, 3};
boolean equal = Arrays.equals(arr1, arr2);
// true // Deep equals for multi-dimensional arrays int[][] m1 = {{1, 2}, {3, 4}};
int[][] m2 = {{1, 2}, {3, 4}};
boolean deepEqual = Arrays.deepEquals(m1, m2);
// true

7.2 Arrays.stream()

Example:
import java.util.Arrays;
int[] numbers = {1, 2, 3, 4, 5};
// Convert array to stream Arrays.stream(numbers) .filter(n -> n % 2 == 0) .forEach(System.out::println);
// 2, 4 // Sum using stream int sum = Arrays.stream(numbers).sum();
// 15 // Average double avg = Arrays.stream(numbers).average().orElse(0.0);
// 3.0

8. Array Limitations

8.1 Fixed Size

Arrays have a fixed size that cannot be changed after creation. To resize, you must create a new array.

Example:
int[] arr = new int[5];
// arr.length = 10;
// Compilation error - length is final // To resize, create new array int[] resized = Arrays.copyOf(arr, 10);
// New array with size
10

8.2 No Built-in Methods

Arrays don't have methods like collections. Use Arrays utility class or convert to collections.

Note: For dynamic sizing and more operations, consider using ArrayList or other collections.

9. Exam Key Points

Critical Concepts for OCP 21 Exam:

  • Array Declaration: type[] name or type name[]
  • Array Creation: new type[size] or {values}
  • Fixed Size: Array size cannot be changed after creation
  • Zero-Based Index: Indices start at 0, go up to length-1
  • length Field: array.length (not a method)
  • Default Values: Primitives = 0/false, Objects = null
  • ArrayIndexOutOfBoundsException: Thrown when accessing invalid index
  • Multi-Dimensional: Arrays of arrays, can be jagged
  • Jagged Arrays: Rows can have different lengths
  • Arrays.sort(): Sorts array in place
  • Arrays.binarySearch(): Requires sorted array
  • Arrays.equals(): Compares array contents
  • Arrays.copyOf(): Creates copy of array
  • Arrays.toString(): Converts array to string
  • Arrays.deepToString(): For multi-dimensional arrays
  • System.arraycopy(): Efficient array copying
  • Arrays.stream(): Convert array to stream (Java 8+)
  • Array Reference: Arrays are objects, == compares references
  • Shorthand Initialization: Only in declaration: int[] arr = {1,2,3}

Post a Comment

0 Comments