Java Arrays
An array is an object that stores a fixed number of values of the same type in contiguous memory. Indexing starts at 0.
Declaring and Initialising
int[] a = new int[5]; // 5 elements, all 0
int[] b = {10, 20, 30, 40}; // literal
System.out.println(b.length); // 4
Example: Largest Element
int[] marks = {45, 78, 91, 66, 83};
int max = marks[0];
for (int m : marks) {
if (m > max) max = m;
}
System.out.println("Largest: " + max);
Largest: 91
2D Array (Matrix)
int[][] m = { {1, 2, 3}, {4, 5, 6} };
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[i].length; j++) {
System.out.print(m[i][j] + " ");
}
System.out.println();
}
1 2 3
4 5 6
Watch outAccessing
a[a.length] throws ArrayIndexOutOfBoundsException.Track your progress through the Java course