Java Arrays
A variable holds one value. When you need many values of the same kind, such as the marks of 30 students or the temperatures of a week, you use an array: a numbered row of boxes, all of the same type, stored under one name.
Creating an array
You can create an array with its values in curly brackets, or create an empty array of a given size with new:
public class Main {
public static void main(String[] args) {
String[] fruits = {"apple", "banana", "cherry"};
int[] marks = new int[4];
marks[0] = 78;
marks[1] = 92;
System.out.println(fruits[0]);
System.out.println(fruits.length);
System.out.println(marks[1] + " " + marks[3]);
}
}apple 3 92 0
- The type is written with square brackets:
String[],int[]. - Elements are numbered from 0, just like the characters of a string. The first element is
fruits[0], the last isfruits[fruits.length - 1]. length(without brackets) gives the number of elements. An array's length never changes.- Elements of a new number array start as 0, of a
booleanarray asfalse, and of aStringarray asnull.
Changing elements and going out of range
public class Main {
public static void main(String[] args) {
int[] days = {31, 28, 31};
days[1] = 29;
System.out.println(days[1]);
System.out.println(days[3]);
}
}29 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3 at Main.main(Main.java:6)
Asking for an index that does not exist stops the program with an ArrayIndexOutOfBoundsException, and the message tells you the bad index and the length.
Looping over an array
A for loop can visit every index. When you only need the values, the for-each loop is simpler: read it as "for each value in the array":
public class Main {
public static void main(String[] args) {
int[] prices = {120, 45, 300, 80};
for (int i = 0; i < prices.length; i++) {
System.out.println("Item " + i + ": " + prices[i]);
}
int total = 0;
for (int p : prices) {
total += p;
}
System.out.println("Total: " + total);
}
}Item 0: 120 Item 1: 45 Item 2: 300 Item 3: 80 Total: 545
Use the index loop when you need the position or want to change elements; use for-each when you just read the values.
Finding the largest value
A classic task: keep the best value seen so far and compare every element with it.
public class Main {
public static void main(String[] args) {
double[] temps = {28.5, 31.2, 29.8, 33.1, 30.0};
double max = temps[0];
for (double t : temps) {
if (t > max) {
max = t;
}
}
System.out.println("Hottest: " + max);
}
}Hottest: 33.1
Starting with the first element (instead of 0) makes the code correct even when all values are negative. The next topic, Arrays Class, shows ready-made methods for printing, sorting and searching arrays.
Practice exercises
- Store the names of five friends in an array and print them in reverse order.
- Store seven daily step counts and print the average.
- Count how many numbers in
{4, 9, 12, 7, 18, 3}are even.