Sub topic 1
What an Array Is
A group of values
A Java array is a fixed-size group of values of the same type. Each value has its own place in the group. A value in an array is called an element.
A type describes what kind of value Java can use. For example, int is a type for whole numbers within a limited range. An array of int values can hold scores such as 80, 90, and 100.
Arrays are useful when values belong together. Imagine keeping track of three test scores. You could give each score a separate name, but an array lets you keep the scores together under one name. Java also provides ways to work with the values as a group.
Think of an array as boxes
Picture an array as a row of boxes. Each box holds one element:
| Place in the array | First | Second | Third |
|---|---|---|---|
| Score | 80 | 90 | 100 |
The order matters. In this example, 80 is the first score and 100 is the third.
The number of boxes is the array’s size. You choose that size when you create the array. Once the array exists, its size cannot change. An array can also have zero elements.
You can, however, change a value in a box. For example, you can replace the first score with 85. The array still has three boxes.
Worked example
This program creates an array of three scores. It then shows the array’s size and changes one score.
Save the program in a file named ScoresDemo.java.
public class ScoresDemo {
public static void main(String[] args) {
int[] scores = {80, 90, 100};
System.out.println("Number of scores: " + scores.length);
System.out.println("First score: " + scores[0]);
scores[0] = 85;
System.out.println("New first score: " + scores[0]);
System.out.println("Number of scores: " + scores.length);
}
}With Java 11 or later installed, run the file with this command:
java ScoresDemo.javaThe output is:
Number of scores: 3
First score: 80
New first score: 85
Number of scores: 3Here is what the important parts mean:
int[]tells Java that the array holds whole numbers.scoresis the name used to refer to the array.- The values inside
{ }are its starting elements. scores.lengthgives the number of places in the array.scores[0]means the first element.
The number inside the square brackets is an index. An index identifies a place in an array. Java starts counting these places at 0, so index 0 is the first place.
The program changes the first score from 80 to 85. Notice that the size stays at 3.
When an array helps
An array is a good fit when you have a group of related values of one type and know how many places you need. For example, you might use one for the temperatures recorded over seven days or the scores from three tests.
The array keeps those values together and in order. Each value still has its own place, so changing one does not replace the others.
Check your understanding
Exercise
An array holds the scores 80, 90, and 100. If you replace 90 with 95, how many elements does the array have?
Show answer
Three. Replacing a value changes an element, not the size of the array.