β Javaπ
Day 8
Arrays in Java
Declare, initialize and access single-dimensional and 2D arrays in Java.
π―
Learning objectives
- βDeclare and initialize arrays two ways
- βAccess, modify and iterate array elements
- βWork with 2D arrays (matrices)
π‘ Key points
- Array = fixed-size, ordered collection of same-type elements.
- Zero-indexed: valid indices 0 to length - 1.
- arr.length is a field (no parentheses), unlike String's length().
- Once created, size cannot change. For dynamic sizing use ArrayList.
π» Code examples(4)
#1Declare and initialize
javaint[] a = new int[5]; // {0, 0, 0, 0, 0}
int[] b = {10, 20, 30, 40, 50}; // literal
int[] c = new int[]{1, 2, 3}; // long form
String[] names = {"Amit", "Priya", "Ravi"};
new int[5] creates 5 slots initialized to 0. Literals infer size from list.
#2Access and modify
javaint[] marks = {85, 90, 78};
System.out.println(marks[0]); // 85
marks[2] = 95; // update
System.out.println(marks.length); // 3
Reading marks[3] throws ArrayIndexOutOfBoundsException β always index < length.
#3Iterate β two ways
javaint[] arr = {5, 10, 15};
// index-based (need i for position)
for (int i = 0; i < arr.length; i++) {
System.out.println(i + ": " + arr[i]);
}
// for-each (cleaner when index not needed)
for (int x : arr) {
System.out.println(x);
}
Prefer for-each unless you need the index or want to modify elements by index.
#42D array (matrix)
javaint[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
};
System.out.println(grid[1][2]); // 6
for (int[] row : grid) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
int[][] = array of arrays. grid[row][col] to access. Rows can even have different lengths (jagged array).
π― Practice
Q1. What is the default value of int[] arr = new int[3]?+
All slots default to 0. Boolean arrays default to false, object arrays to null.
Q2. Find the largest element in int[] nums = {3, 8, 1, 12, 5}.+
int max = nums[0]; for (int n : nums) if (n > max) max = n; // max = 12
Q3. Why is int[] length a field but String's length() a method?+
Arrays are special language constructs with length exposed directly. String is a class β length() is a proper method.
π Notes
Common operations
// sum
int sum = 0;
for (int x : arr) sum += x;
// reverse in place
for (int i = 0, j = arr.length - 1; i < j; i++, j--) {
int t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}
// copy
int[] copy = arr.clone();
// sort
java.util.Arrays.sort(arr);
Array vs ArrayList
| | Array | ArrayList |
|---|---|---|
| Size | Fixed | Grows/shrinks |
| Type | Any (primitive OK) | Objects only |
| Methods | .length, indexing | rich API (add, remove, contains) |
| Speed | Faster | Slightly slower |
Rule of thumb: fixed-size numeric data β array. Everything else β ArrayList.