Arrays

Introduction to Arrays

  • Primitive variables hold only one value at a time.

  • Arrays store collections of like-typed values with indexing.

  • Arrays can store any single data type at a time.

  • Arrays are ordered lists of data elements.

Creating Arrays

  • Arrays are objects requiring an object reference.

  • Declaration: int[] numbers;

  • Creation: numbers = new int[6]; (initializes elements to 0).

  • Array indexes start at 0.

  • Declaration and creation combined: int[] numbers = new int[6];

  • Arrays can be of any type (e.g., float[], char[], long[], double[]).

  • Array size must be a non-negative number (literal, constant, or variable).

final int ARRAY_SIZE = 6;
int[] numbers = new int[ARRAY_SIZE];
  • Array size is fixed after creation.

Accessing Array Elements

  • Access via reference name and subscript (index).

  • numbers[0] = 20;

Inputting and Outputting Array Elements

  • Array elements are treated like any other variable, accessed by name and subscript.

  • Array subscripts can be variables (e.g., loop counters).

Bounds Checking

  • Array indexes range from 0 to (array length - 1).

  • Example: int values = new int[10]; (indexes 0-9).

  • Use i, j, k as counting variables in loops, where i can represent "index".

Off-by-One Errors

  • Common error when accessing arrays.

int[] numbers = new int[100];
for (int i = 1; i <= 100; i++)
    numbers[i] = 99; // results in ArrayIndexOutOfBoundsException
  • The above code throws an ArrayIndexOutOfBoundsException because the loop iterates one element beyond the valid index range.

Array Initialization

  • Initialization lists can initialize arrays with known values.
    int[] days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  • Values are assigned in order: days[0] is 31, days[1] is 28, etc.

Alternate Array Declaration

  • Brackets can be placed after the variable name: int numbers[]; (less common).

  • Multiple arrays can be declared on the same line: int[] numbers, codes, scores;

  • With the alternate notation, each variable must have brackets: int numbers[], codes[], scores; (scores is just an int variable).

Processing Array Contents

  • Array elements are processed like other variables.

  • Example: grossPay = hours[3] * payRate;

  • Pre/post increment operators work: ++score[2];, score[4]++;

  • Array elements can be used in relational operations and loop conditions.

Array Length

  • Arrays are objects with a public length field (constant).

  • Example: double[] temperatures = new double[25]; (length is 25).

  • Access length via temperatures.length.

The Enhanced for Loop

  • Simplified array processing (read-only).

  • Iterates through all elements.

  • Syntax: for (datatype elementVariable : array) statement;
    Example:

```java
int[] numbers = {3, 6, 9};
for (int val : numbers) {
System.out.println(