Java Arrays
An array is a variable that holds many values of one type in a fixed order. Each value sits at a numbered index, and the first index is 0.
Create an array and read by index
The array holds three scores. Index 0 reads the first score and index 1 reads the second.
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 70};
System.out.println(scores[0]);
System.out.println(scores[1]);
}
}Change one element
The assignment targets index 1 only. The print line then reads that same index.
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 70};
scores[1] = 95;
System.out.println(scores[1]);
}
}Count the elements
The length field reports how many elements the array holds. This array holds four prices.
public class Main {
public static void main(String[] args) {
int[] prices = {4, 9, 12, 7};
System.out.println(prices.length);
}
}Print all elements with a for loop
The counter runs from 0 to the last index. Each pass prints the element at that index.
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 70};
for (int i = 0; i < scores.length; i++) {
System.out.println(scores[i]);
}
}
}Print all elements with a for-each loop
The for-each loop hands over one element per pass. No index is written here.
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 70};
for (int score : scores) {
System.out.println(score);
}
}
}Example
public class Main {
public static void main(String[] args) {
int[] scores = {80, 90, 70, 100};
int total = 0;
for (int score : scores) {
total += score;
}
double average = (double) total / scores.length;
System.out.println(total);
System.out.println(average);
}
}Key points
- The values of an array are listed inside curly braces.
- An index in square brackets reads one element.
- An index with an assignment changes one element.
- The length field counts the elements, and it takes no parentheses.
- A for-each loop visits each element without an index.
In this example, the for-each loop adds each score to total. The total reaches 340 after four passes. The average line casts total to double before the division. The printed average is 85.0.
Note
Printing an array variable prints an identity code, not its values.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Java Compiler
Exercise
What is the index of the first element in an array?