Loops and arrays
Arrays have a fixed length set when they are created, and indexes start at 0. Reading index arr.length throws ArrayIndexOutOfBoundsException.
Java has four loops:
forwhen you need the index.- enhanced for (
for (T x : items), Java 5) to read every element. whilewhen you don't know how many rounds you need.do-whilewhen the body must run at least once.
break leaves a loop; continue skips to the next round. For a list that grows, use ArrayList. For sorting and searching arrays, use the Arrays utility class.
Creating arrays
An array has a fixed length set when it's created. Elements get default values (0, false or null). Indexes run from 0 to length - 1; going outside throws ArrayIndexOutOfBoundsException.
int[] marks = new int[5]; // [0, 0, 0, 0, 0]
String[] cities = {"Pune", "Delhi"};
marks[0] = 91;
System.out.println(marks.length); // 5 (a field, not a method)
System.out.println(marks[5]); // ArrayIndexOutOfBoundsExceptionLooping over arrays
Use for-each when you only read values, and an index loop when you need the position or want to change elements.
int sum = 0;
for (int m : marks) sum += m;
for (int i = 0; i < marks.length; i++) {
marks[i] = marks[i] + 5; // bonus marks
}Two-dimensional and jagged arrays
A 2D array is an array of arrays. Rows can have different lengths (a jagged array).
int[][] grid = new int[3][4]; // 3 rows, 4 columns
grid[1][2] = 7;
int[][] triangle = new int[3][];
for (int r = 0; r < 3; r++) triangle[r] = new int[r + 1];
System.out.println(Arrays.deepToString(grid));The Arrays utility class
java.util.Arrays has the everyday helpers: toString, sort, binarySearch (on sorted arrays), fill, copyOf, copyOfRange, equals and stream. Arrays.asList returns a fixed-size list backed by the array: add throws UnsupportedOperationException.
int[] a = {5, 2, 9, 1};
Arrays.sort(a); // [1, 2, 5, 9]
int pos = Arrays.binarySearch(a, 5); // 2
int[] bigger = Arrays.copyOf(a, 6); // [1, 2, 5, 9, 0, 0]
Arrays.fill(bigger, -1);
System.out.println(Arrays.toString(a));
int total = Arrays.stream(a).sum();
List<String> fixed = Arrays.asList("a", "b");
// fixed.add("c"); // UnsupportedOperationExceptionArrays vs ArrayList
- Array: fixed size, can hold primitives, slightly faster, simple syntax.
- ArrayList: grows as needed, has rich methods (
add,remove,contains), works with streams and generics, but holds objects only (sointvalues are boxed).
In business code, use List; use arrays for fixed-size data, performance-critical loops or APIs that require them.
Common array tasks
Finding the maximum, reversing in place and checking for a value are classic warm-up problems in interviews.
int max = a[0];
for (int x : a) if (x > max) max = x;
for (int i = 0, j = a.length - 1; i < j; i++, j--) { // reverse in place
int tmp = a[i]; a[i] = a[j]; a[j] = tmp;
}
boolean hasNine = Arrays.stream(a).anyMatch(x -> x == 9);Example
int[] marks = {72, 88, 95, 60};
int total = 0;
for (int m : marks) { // enhanced for
total += m;
}
double avg = (double) total / marks.length;
Arrays.sort(marks); // [60, 72, 88, 95]
System.out.println(Arrays.toString(marks));
int[][] grid = new int[3][3]; // 2D array
grid[1][2] = 5;Common mistake
Printing an array with System.out.println(arr) shows something like [I@1b6d3586. Use Arrays.toString(arr) instead.
Under the hood
Arrays are objects on the heap with a length field. They are covariant: a String array can be assigned to an Object array variable, which can then throw ArrayStoreException at runtime. Generics are deliberately invariant to avoid exactly this. For hot loops over numbers, a primitive array beats List<Integer> because there is no boxing.
Check yourself
What is the last valid index of new int[5]?
How this connects
Know these first
Part of Java from zero.
Was this lesson helpful?
Finished reading? Mark it complete to track your progress.