AI Hints
Home›Java Tutorial›What an Array Is, Creating Arrays and Looping Over Arrays
Java · Lesson 46 of 120

What an Array Is

Many values in one variable.

⏱ 2 min read▶ Video at 57:45🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

What if you need to store fifty test scores? Fifty separate variables would be painful. An array holds many values of the same type, in one variable.

  • Fifty scores?
  • Not fifty variables
  • One array

An array in a picture

Think of an array as a row of numbered boxes. Every box holds the same type of value. The boxes are numbered from zero. And the number of boxes is fixed, once the array is created.

keyvalue
A row of boxesone variable
Same typeall ints, or all Strings
Numberedfrom 0
Fixed sizeset when created

Using an array

Square brackets after int mean an array of ints. Curly braces list the starting values. Scores, then a position in square brackets, reads one box. Length tells us how many boxes there are. And we can change a box, by assigning to it. Run it. The first score is seventy two. The third, at position two, is ninety. There are five, and the fourth is now seventy.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[] scores = {72, 85, 90, 64, 78};
        System.out.println("First score: " + scores[0]);
        System.out.println("Third score: " + scores[2]);
        System.out.println("How many: " + scores.length);
        scores[3] = 70;
        System.out.println("Fourth score is now " + scores[3]);
    }
}
Output
First score: 72
Third score: 90
How many: 5
Fourth score is now 70

Summary

An array is a fixed row of boxes, all the same type, numbered from zero. Next, the different ways to create one.

Key takeaways
  • int[] scores
  • scores[0] is first
  • scores.length
Next up: Creating Arrays — values or new