What an array is and why you need one
An array in Java is a container that holds multiple values of the same type in a single variable. Instead of creating ten separate variables to store ten numbers, you create one array that holds all ten. Arrays are useful because they let you work with groups of related data — like a list of IP addresses on your network, a set of port numbers, or a collection of device names — without cluttering your code with dozens of individual variables.
Arrays are one of the most common data structures in Java. Once you create an array, you can loop through it, search it, sort it, or pass it to other parts of your program. Understanding how to create and use arrays is essential before you move on to more complex data structures.
Key Takeaways
- Arrays are declared with square brackets and a data type, then created with the new keyword followed by the size in brackets.
- You can initialize an array with values at the same time you create it by listing the values inside curly braces.
- Array positions are numbered starting from zero, so the first element is at index 0, not index 1.
- You access individual elements by writing the array name followed by the index number in square brackets.
The basic syntax for declaring and creating an array
To create an array in Java, you need two steps: declare the array and initialize it. The declaration tells Java what type of data the array will hold. The initialization actually creates the array in memory and sets its size.
Here is the basic pattern:
int[] numbers = new int[5];
Breaking this down: int[] declares that you are creating an array of integers. numbers is the name of the array. new int[5] creates the array with space for 5 elements. The square brackets with the number inside tell Java how many items the array can hold.
You can use any data type: String[] for text, double[] for decimal numbers, boolean[] for true/false values, or char[] for single characters. The pattern stays the same — type, square brackets, name, equals sign, new, type again, square brackets with size.
Creating an array with initial values
If you already know what values you want in the array, you can declare and initialize it in one line by listing the values inside curly braces. Java will automatically figure out the array size based on how many values you provide.
String[] devices = {"Router", "Switch", "Firewall", "Server"}; int[] ports = {22, 80, 443, 8080, 3306};
In the first example, Java creates a String array with 4 elements. In the second, it creates an int array with 5 elements. You do not need to write new or specify a size when you use this syntax — Java handles it automatically.
This approach is faster when you know your values ahead of time. If you do not know the values yet but know how many elements you need, use the first method with new and a size instead.
Understanding array indexes and accessing elements
Arrays are zero-indexed, meaning the first element is at position 0, not position 1. If you create an array with 5 elements, the valid indexes are 0, 1, 2, 3, and 4. Trying to access index 5 will cause an error.
To get a value from an array, write the array name followed by the index in square brackets:
String[] devices = {"Router", "Switch", "Firewall"}; System.out.println(devices[0]); // prints "Router" System.out.println(devices[1]); // prints "Switch" System.out.println(devices[2]); // prints "Firewall"
To change a value, use the same syntax with an equals sign:
devices[1] = "Gateway"; System.out.println(devices[1]); // now prints "Gateway"
You can also use a variable as the index, which is how you loop through arrays. If i is 0, then devices[i] refers to the first element. If i is 1, it refers to the second element, and so on.
Looping through an array with a for loop
The most common way to work with every element in an array is to use a for loop. You start at index 0 and count up to the last valid index. The array's length property tells you how many elements it contains.
int[] ports = {22, 80, 443, 8080}; for (int i = 0; i < ports.length; i++) { System.out.println(ports[i]); }
This loop starts with i = 0, prints the element at index 0, then increments i to 1, prints the element at index 1, and continues until i reaches the array length. Since ports.length is 4, the loop stops when i reaches 4 (because the condition i < ports.length becomes false).
Java also offers an enhanced for loop (sometimes called a "for-each" loop) that is simpler when you do not need the index number:
for (int port : ports) { System.out.println(port); }
This syntax reads as "for each port in ports" and automatically moves through every element without you having to manage the index yourself.
Common mistakes when working with arrays
The most frequent error is forgetting that arrays are zero-indexed. If you have an array of 5 elements and try to access array[5], Java throws an ArrayIndexOutOfBoundsException because index 5 does not exist.
Another common mistake is confusing the array size with the last valid index. If you create new int[10], the array has 10 elements, but the last index is 9. When looping, always use i < array.length, not i <= array.length.
A third mistake is trying to change an array's size after you create it. Arrays have a fixed length in Java. If you need a container that grows or shrinks, you would use an ArrayList instead, but that is a separate topic. Once you create an array with a specific size, that size does not change.
Frequently Asked Questions
Can I create an array without specifying a size?
No, arrays must have a fixed size when you create them. You either specify the size with new int[10] or provide initial values with curly braces, which automatically sets the size. If you need a container that grows dynamically, use an ArrayList instead.
What happens if I try to access an index that does not exist?
Java throws an ArrayIndexOutOfBoundsException and your program stops. Always check that your index is between 0 and array.length - 1 before accessing an element, or use a loop that automatically stays within bounds.
Can an array hold different data types?
No, all elements in an array must be the same type. An int[] holds only integers, a String[] holds only strings. If you need to store mixed types, you would use an Object[] array or a more complex data structure like a class or a map.
How do I find the length of an array?
Use the length property: array.length returns the number of elements. This is useful in loops to avoid accessing indexes that do not exist. Note that length is a property, not a method, so you do not write array.length().