Arrays
## Learning Objectives
- Create and initialize arrays
- Access and modify array elements
- Iterate over arrays
- Work with multi-dimensional arrays
## Declaring Arrays
### Syntax
```java
// Declaration
int[] numbers; // Preferred
int numbers[]; // Also valid (C-style)
// Creation
numbers = new int[5];
// Declaration + Creation
int[] numbers = new int[5];
```
### Initialization
```java
// By size (default values)
int[] numbers = new int[3];
// [0, 0, 0]
boolean[] flags = new boolean[2];
// [false, false]
String[] names = new String[2];
// [null, null]
// With values
int[] numbers = {1, 2, 3, 4, 5};
String[] fruits = {"Apple", "Banana", "Orange"};
```
## Array Length
```java
int[] numbers = {1, 2, 3, 4, 5};
System.out.println(numbers.length); // 5
```
## Accessing Elements
### Index
```java
int[] numbers = {10, 20, 30, 40, 50};
System.out.println(numbers[0]); // First element: 10
System.out.println(numbers[4]); // Last element: 50
System.out.println(numbers[numbers.length - 1]); // Last element
```
### Modifying Elements
```java
int[] numbers = {10, 20, 30};
numbers[0] = 15; // Change first element
numbers[2] = 35; // Change last element
```
### ArrayIndexOutOfBoundsException
```java
int[] numbers = {1, 2, 3};
// numbers[5] = 10; // Runtime error!
```
## Iterating Arrays
### for Loop
```java
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
```
### Enhanced for-each
```java
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
```
### While Loop
```java
int[] numbers = {1, 2, 3, 4, 5};
int i = 0;
while (i < numbers.length) {
System.out.println(numbers[i]);
i++;
}
```
## Common Operations
### Sum and Average
```java
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int num : numbers) {
sum += num;
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum + ", Average: " + average);
```
### Find Maximum
```java
int[] numbers = {3, 7, 2, 9, 4};
int max = numbers[0];
for (int num : numbers) {
if (num > max) {
max = num;
}
}
System.out.println("Max: " + max);
```
### Count Matches
```java
int[] numbers = {1, 2, 3, 2, 4, 2, 5};
int target = 2;
int count = 0;
for (int num : numbers) {
if (num == target) {
count++;
}
}
System.out.println("Count: " + count);
```
## Arrays Utility Class
### java.util.Arrays
```java
import java.util.Arrays;
// Sort
int[] numbers = {3, 1, 4, 1, 5, 9};
Arrays.sort(numbers);
// Fill
int[] arr = new int[5];
Arrays.fill(arr, 10); // [10, 10, 10, 10, 10]
// Binary Search (must be sorted)
int index = Arrays.binarySearch(numbers, 4);
// Copy
int[] copy = Arrays.copyOf(numbers, numbers.length);
int[] partial = Arrays.copyOf(numbers, 3);
// Compare
boolean equal = Arrays.equals(arr1, arr2);
// toString
System.out.println(Arrays.toString(numbers));
```
## Two-Dimensional Arrays
### Declaration
```java
int[][] matrix = new int[3][4]; // 3 rows, 4 columns
```
### Matrix Initialization
```java
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
```
### Accessing
```java
System.out.println(matrix[0][0]); // First element: 1
System.out.println(matrix[2][2]); // Last element: 9
matrix[1][2] = 10; // Modify element
```
### Iterating
```java
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%d ", matrix[i][j]);
}
System.out.println();
}
```
### Matrix for-each
```java
for (int[] row : matrix) {
for (int num : row) {
System.out.printf("%d ", num);
}
System.out.println();
}
```
## Jagged Arrays
### Different Row Lengths
```java
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // 2 elements
jagged[1] = new int[4]; // 4 elements
jagged[2] = new int[1]; // 1 element
// Or with initialization
int[][] jagged = {
{1, 2},
{3, 4, 5, 6},
{7}
};
```
## Arrays vs ArrayList
| Feature | Array | ArrayList |
|---------|-------|-----------|
| Size | Fixed | Dynamic |
| Performance | Faster | Slightly slower |
| Type | Primitives & Objects | Objects only |
| API | Limited | Rich methods |
## Summary
- Arrays: `type[] name = new type[size]` or `type[] name = {values}`
- Access: `array[index]`
- Length: `array.length` (property, not method)
- Iterate: regular for loop or enhanced for-each
- Arrays utility: sort, fill, copy, binarySearch, equals
- 2D arrays: `int[][] matrix = new int[rows][cols]`
- Arrays have fixed size; use ArrayList for dynamic collections
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →