Arrays
An array holds a fixed number of values of one type:
int[] numbers = {1, 2, 3, 4, 5};.
Example: an enhanced for-loop over an array
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int total = 0;
for (int n : numbers) {
total += n;
}
System.out.println("Total: " + total);
}
}
Total: 15
for (int n : numbers) — read "for each int n in
numbers" — is Java's enhanced for-loop, and is generally
preferred over a manual index-based loop whenever you don't actually need
the index itself, just each value in turn. Access individual items by
zero-based index (numbers[0]), and get the length with
numbers.length — a field, not a method, so no parentheses.
public class Main {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
int total = 0;
for (int n : numbers) {
total += n;
}
System.out.println("Total: " + total);
}
}
Total: 15