Java Tutorial
Java Arrays
An array is a fixed list of values of one type. Index from 0. Do not walk off the end.
Fixed length
int[] nums = {8, 11, 5} creates an array of length 3. nums.length is that length. You cannot append. For a growing list, use ArrayList later.
Example
public class Main {
public static void main(String[] args) {
int[] nums = {8, 11, 5};
int sum = 0;
for (int n : nums) sum += n;
System.out.println(sum);
}
}Index from 0
The first slot is nums[0]. The last is nums[nums.length - 1]. An index of nums.length throws ArrayIndexOutOfBoundsException.
Example
public class Main {
public static void main(String[] args) {
int[] nums = {4, 17, 9, 2, 13};
int best = nums[0];
for (int n : nums) if (n > best) best = n;
System.out.println(best);
}
}new int[n] then fill it
new int[4] makes four slots, each starting at 0. Fill them in a loop when the values are not known when you declare the array.
Example
public class Main {
public static void main(String[] args) {
int[] squares = new int[5];
for (int i = 0; i < squares.length; i++) {
squares[i] = (i + 1) * (i + 1);
}
System.out.println(java.util.Arrays.toString(squares));
}
}java.util.Arrays.toString(arr) prints an array as [1, 4, 9, 16, 25]. Printing the array directly shows a cryptic [I@1b6d3586 instead — a common surprise for beginners.
Stay inside the bounds
Valid indexes run from 0 to length - 1. Reach for nums[nums.length] and Java throws ArrayIndexOutOfBoundsException at runtime — there is no slot there.
The last element is nums[nums.length - 1], not nums[nums.length]. Off-by-one at the end of an array is one of the most common runtime crashes in Java.
Try It Yourself
Exercise: Given int[] nums = {4, 8, 15, 16, 23}, compute and print the average as a double.
Show solution
int[] nums = {4, 8, 15, 16, 23};
int sum = 0;
for (int n : nums) sum += n;
System.out.println((double) sum / nums.length); // 13.2The cast to double matters — sum / nums.length with two ints would truncate to 13.
Key Takeaways
- An array has a fixed length;
arr.lengthis how many slots it has. - Indexes run
0tolength - 1— going past the end throws at runtime. new int[n]makes n zeros to fill later;{...}sets values up front.- Use
Arrays.toString(arr)to print an array readably.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the Java editor at /java/try. Change one measurement and check whether the result still has the right unit.
Chemistry
Titre mean
Three titre volumes sit in an array. Sum them, divide by length, print the mean.
Example
public class Main {
public static void main(String[] args) {
double[] ml = {24.6, 24.7, 24.6};
double s = 0;
for (double v : ml) s += v;
System.out.println(s / ml.length);
}
}