Why arrays?
To store the marks of 60 students you would need 60 variables. An array stores many values of the same type under one name, each in a numbered slot.
Creating an array
int[] marks = new int[5]; // 5 slots, all 0
String[] names = {"Asha", "Ravi", "Meena"}; // created and filled
double[] prices = new double[] {9.5, 12.0, 4.25};
int[] marksdeclares the array variable. (int marks[]also works but is less common.)new int[5]creates 5 slots. The size is fixed once the array is created.- New slots get default values:
0for numbers,falseforboolean,'\u0000'forchar,nullfor objects such asString.
Indexes and length
Slots are numbered from 0 to length - 1:
int[] marks = {78, 91, 65, 84, 70};
System.out.println(marks[0]); // 78 (first)
System.out.println(marks[4]); // 70 (last)
marks[2] = 68; // change the third value
System.out.println(marks.length); // 5
length is a field, not a method: no brackets. Reading marks[5] throws ArrayIndexOutOfBoundsException.
Looping over an array
With a classic for loop, when you need the index:
for (int i = 0; i < marks.length; i++) {
System.out.println("Student " + (i + 1) + ": " + marks[i]);
}
With a for-each loop, when you only need the values:
int total = 0;
for (int m : marks) {
total += m;
}
double average = (double) total / marks.length;
Read for (int m : marks) as "for each m in marks". A for-each loop cannot change the slots.
Common array tasks
Largest and smallest
int max = marks[0], min = marks[0];
for (int m : marks) {
if (m > max) max = m;
if (m < min) min = m;
}
Linear search
int target = 84, foundAt = -1;
for (int i = 0; i < marks.length; i++) {
if (marks[i] == target) {
foundAt = i;
break;
}
}
System.out.println(foundAt == -1 ? "Not found" : "Found at index " + foundAt);
Bubble sort
Compare neighbours and swap them when they are in the wrong order. After each pass the largest remaining value has "bubbled" to the end.
int[] a = {5, 2, 9, 1, 6};
for (int pass = 0; pass < a.length - 1; pass++) {
for (int i = 0; i < a.length - 1 - pass; i++) {
if (a[i] > a[i + 1]) {
int temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
// a is now 1 2 5 6 9
The Arrays class
java.util.Arrays has ready-made helpers:
import java.util.Arrays;
int[] a = {5, 2, 9, 1, 6};
Arrays.sort(a); // [1, 2, 5, 6, 9]
System.out.println(Arrays.toString(a)); // prints [1, 2, 5, 6, 9]
int pos = Arrays.binarySearch(a, 6); // 3 (array must be sorted)
int[] copy = Arrays.copyOf(a, 7); // [1, 2, 5, 6, 9, 0, 0]
int[] filled = new int[4];
Arrays.fill(filled, 7); // [7, 7, 7, 7]
boolean same = Arrays.equals(a, copy); // false
Printing an array directly, System.out.println(a), shows something like [I@1b6d3586. Use Arrays.toString(a) instead.
Arrays and methods
An array variable holds a reference. Passing it to a method passes a copy of that reference, so the method works on the same array:
static void addGrace(int[] marks) {
for (int i = 0; i < marks.length; i++) marks[i] += 2;
}
int[] m = {38, 50};
addGrace(m);
System.out.println(Arrays.toString(m)); // [40, 52]
Assigning int[] b = a; also copies only the reference: a and b are the same array. Use a.clone() or Arrays.copyOf for a real copy.
2D arrays
A 2D array is an array of rows: a table or a matrix.
int[][] grid = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(grid[1][2]); // 6 (row 1, column 2)
System.out.println(grid.length); // 2 rows
System.out.println(grid[0].length); // 3 columns
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
System.out.print(grid[r][c] + " ");
}
System.out.println();
}
Matrix addition
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] sum = new int[2][2];
for (int r = 0; r < 2; r++)
for (int c = 0; c < 2; c++)
sum[r][c] = a[r][c] + b[r][c];
// sum is {{6, 8}, {10, 12}}
Rows can have different lengths (a jagged array): int[][] j = new int[3][]; j[0] = new int[2];.
Common mistakes
- Using
i <= a.lengthin a loop: the last index islength - 1. - Writing
a.length(): for arrays it isa.length;length()is for strings. - Printing an array with
println(a)instead ofArrays.toString(a). - Thinking
b = acopies the array. - Calling
Arrays.binarySearchon an unsorted array: the result is meaningless.
Key points
- An array holds a fixed number of values of one type; indexes run from 0 to
length - 1. new int[n]fills with default values;{...}creates and fills.- Use for-each to read every value and a classic
forwhen you need the index or want to change slots. Arrays.sort,Arrays.toString,Arrays.binarySearch,Arrays.copyOfandArrays.fillsave time.- Array variables hold references; methods can change the array's contents.
- A 2D array is
type[rows][cols], accessed asa[r][c].
Practice questions
1. What are the default values in new boolean[3] and new String[2]?
[false, false, false] and [null, null].
2. Reverse an array in place.
int[] a = {1, 2, 3, 4, 5};
for (int i = 0, j = a.length - 1; i < j; i++, j--) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}3. Count how many students scored 75 or more in int[] marks.
int count = 0;
for (int m : marks) {
if (m >= 75) count++;
}4. Print the sum of each row of a 2D array int[][] sales.
for (int r = 0; r < sales.length; r++) {
int rowSum = 0;
for (int v : sales[r]) rowSum += v;
System.out.println("Row " + r + ": " + rowSum);
}5. What is printed? int[] a = {1, 2}; int[] b = a; b[0] = 9; System.out.println(a[0]);
9. a and b refer to the same array.