Chapter 9: Arrays
Introduction to Arrays
An array is a data structure that stores a collection of elements of the same type, indexed starting at 0.
Declaring Arrays
Arrays can be declared as:
int[] numbers;(preferred)int numbers[];(valid but less common)
Must be initialized with a specific size or values:
int[] numbers = new int[5];(array of 5 integers)int[] numbers = {1, 2, 3, 4, 5};(initialized with values)
Accessing Array Elements
Access elements via their index:
numbers[0]accesses the first element.
Array Length
Use
numbers.lengthto get the number of elements.
Multidimensional Arrays
Arrays can be multidimensional:
Example:
int[][] matrix = new int[3][4];Accessed via multiple indices:
matrix[0][1]
Enhanced For Loop
Simplifies iteration:
for (int num : numbers) { System.out.println(num); }
Passing Arrays to Methods
Arrays are passed by reference:
Example:
public static void printArray(int[] arr) { for (int num : arr) System.out.println(num); }
Common Array Operations
Copying:
System.arraycopy()copies elements.Sorting: Use
Arrays.sort().Searching: Use linear search or binary search (for sorted arrays).
Array of Objects
Can store objects, e.g.,
String[] names = new String[3];.
Array Exceptions
ArrayIndexOutOfBoundsExceptionoccurs for invalid indices (0 to length-1). Always ensure indices are within bounds.
Declaration Example
int i1,i2,i3,i4;Array Syntax:
First, the data type:
int,double,String.Use brackets:
int[] alhsorint alhs[].Example:
int[] alhs = new int[6];The 6 indicates a fixed number of components (must be a positive integer).
Initialization Behavior
Java initializes array components to 0. For a newly created array of size 6, all cells start at 0.
One-dimensional Array Declaration
Example of correct vs. incorrect:
Incorrect:
int alpha[], beta;Correct:
int[] alpha, beta;(applies prison to both)