L8: Arrays

Overview

  • Arrays allow storing collections of values of the same type under a single name, avoiding the need for multiple individual variables.
  • Arrays in Java are fixed-size, ordered sequences of elements, each accessible by an index.

1. What is an Array?

  • An array is an ordered sequence of values, all of which are of the same type.
  • Elements in an array are stored in a contiguous block of memory and are accessed using an index, which starts at 0.

2. What Can Be Stored in an Array?

  • Primitive typesintdoublechar, etc.
  • Object referencesString, custom objects, etc.
  • Other arrays: Allows for multi-dimensional arrays.

3. Declaring and Creating Arrays

  • Declaration: Creates a reference variable for the array.

    int[] numbers;  // Preferred
    int numbers[];  // Valid, but less common
  • Instantiation: Creates the actual array in memory.

    numbers = new int[5];  // Creates an array of 5 integers
  • Combined Declaration and Instantiation:

    double[] weekHighs = new double[7];
    String[] names = {"Alice", "Bob", "Charlie"};
  • Fixed Length: The length of an array is set when it is created and cannot be changed.

4. Array Length

  • Accessed using the .length property (not a method).

    int size = weekHighs.length;

5. Default Values in Arrays

  • Numeric types: Initialized to 0 (e.g., 00.0 for int and double).
  • Boolean: Initialized to false.
  • Object references: Initialized to null.

6. Assigning to a Literal Array

  • Arrays can be directly assigned values using a literal array:

    int[] scores = {85, 90, 78, 88, 92};  // Array of integers
  • This can only be done at the point of declaration.

7. Accessing and Changing Individual Elements

  • Accessing an element:

    int firstNumber = numbers[0];  // Accesses the first element
  • Changing an element:

    numbers[2] = 10;  // Sets the third element to 10

8. The for-each Statement

  • Used to iterate over elements in an array.

  • Syntax:

    for (elementType element : array) {
        // bodyStatement(s)
    }
  • Example:

    for (int number : numbers) {
        System.out.println(number);
    }
  • Notes:

    • Cannot modify the array elements within the loop.
    • Does not provide access to the element index.

9. Array Traversal and Searching

  • Traversal:

    for (int i = 0; i < numbers.length; i++) {
        System.out.println(numbers[i]);
    }
  • Searching for an Element:

    String result = "Not found";
    for (int i = 0; i < numbers.length; i++) {
        if (numbers[i] == searchValue) {
            result = "Found at index " + i;
            break;  // Exit the loop when found
        }
    }

10. NullPointerException and Null Check

  • Arrays of objects may contain null if not explicitly initialized.

  • To avoid NullPointerException:

    if (array != null) {
        for (String item : array) {
            if (item != null) {
                // Process item
            }
        }
    }

11. Ragged Arrays

  • Arrays with rows of different lengths.

  • Example:

    int[][] raggedArray = new int[3][];
    raggedArray[0] = new int[2];  // First row has 2 columns
    raggedArray[1] = new int[4];  // Second row has 4 columns
    raggedArray[2] = new int[3];  // Third row has 3 columns

12. Two-Dimensional Arrays

  • Arrays of arrays, used to represent matrices or tables.

  • Declaration:

    int[][] matrix = new int[3][4];  // 3 rows, 4 columns
  • Accessing and Assigning Elements:

    matrix[1][2] = 5;  // Set element in the second row, third column
    int value = matrix[0][1];  // Access element in the first row, second column
  • Creating and Initializing:

    double[][] array2D = {
        {80, 70, 75},
        {69, 72, 74}
    };

13. 2-D Array Processing

  • Row-major Traversal:

    for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[row].length; col++) {
            System.out.print(matrix[row][col] + " ");
        }
        System.out.println();
    }
  • Column-major Traversal:

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

14. Wrapper Classes

Primitive Data TypeWrapper Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter
  • Wrapper classes (IntegerDouble, etc.) provide object representations for primitive types.
  • Useful in collections, which require objects (e.g., ArrayList<Integer>).

image.png

  • Autoboxing and unboxing allow automatic conversion between primitive types and their wrapper classes:

    Integer[] numbers = {1, 2, 3};
    int sum = 0;
    for (int num : numbers) {  // Automatic unboxing
        sum += num;
    }

15. Arrays Class

  • Utility class in java.util for working with arrays.

  • Common Methods:

    • Arrays.sort(array): Sorts the array.
    • Arrays.binarySearch(array, key): Searches for the key in a sorted array.
    • Arrays.fill(array, value): Fills the array with the specified value.
    • Arrays.equals(array1, array2): Checks if two arrays are equal.
    • Arrays.toString(array): Returns a string representation of the array.
  • Example:

    int[] numbers = {5, 2, 8, 1, 9};
    Arrays.sort(numbers);
    System.out.println(Arrays.toString(numbers));  // Outputs: [1, 2, 5, 8, 9]

Summary

  • Arrays are fixed-size data structures for storing elements of the same type.
  • They can store both primitive types and objects, including other arrays for multi-dimensional use.
  • Use for and for-each loops to traverse arrays, and remember to handle NullPointerExceptions with appropriate checks.
  • The Arrays utility class provides various helpful methods for common array operations.