Arrays hold same-type values
In Java, an array is a collection of values that all have the same type. Once you declare the array, every slot holds the same kind of data, like int or String.
Here is an array of test scores:
int[] scores = {88, 92, 79, 95};
Arrays make it easy to store and loop through many values without making a separate variable for each one.
Declaring and using Java arrays
Java arrays use square brackets []. The type comes before the brackets, so the array knows what kind of values it holds.
String[] names = {"Ada", "Alan", "Grace"};
int[] numbers = new int[5];
The second array creates space for 5 integers, but each value starts as 0 until you set it.
numbers[0] = 10;
numbers[1] = 20;
System.out.println(numbers[0]); // 10
The first item is at index 0. You can find how many items an array holds with .length.
System.out.println(names.length); // 3
Be careful: if you try to use an index that is too big, Java gives you an error.
Build a Java-style array
Enter up to five numbers, and this tool will build the matching Java array code. It will also show the length.
Check yourself
Write a Java array that stores the names of four colors.
Sample answer: String[] colors = {"red", "green", "blue", "yellow"};
A Java arrays example
Java arrays hold a fixed-size collection of the same type. This program creates, fills, and prints an array.
Quick quiz
1. In Java, what does int[] scores declare?
2. What is the first index of a Java array?
3. How do you find how many items are in a Java array?
Keep learning
Arrays are fixed size — next, learn about ArrayLists, Java's list that can grow and shrink while your program runs.