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 multiple test results — without cluttering your code with dozens of individual variable names.
Arrays have a fixed size set when you create them. Once you decide an array will hold 5 items, it always holds exactly 5 slots, even if you only fill 3 of them. This predictability makes arrays fast and memory-efficient, which matters when you're working with network data or system monitoring tasks where performance counts.
Key Takeaways
- Declare an array by writing the data type, square brackets, and a variable name: int[] numbers;
- Create the actual array object using the new keyword and specify how many items it will hold: numbers = new int[5];
- Access each item by its position, starting from 0: the first item is numbers[0], the second is numbers[1], and so on.
- You can declare and create an array in one line: int[] numbers = new int[5];
- Arrays can hold any data type — integers, text strings, objects — as long as all items in one array are the same type.
The two-step process: declaration and creation
Creating an array happens in two separate steps, though you can combine them into one line. The first step is declaration, where you tell Java what type of data the array will hold and give it a name. Write the data type, then square brackets, then the variable name. For example: int[] ports; declares an array that will hold integers and names it ports.
The second step is creation, where you actually build the array object and decide how many slots it will have. Use the new keyword, the data type again, and the size in square brackets. For the ports example: ports = new int[10]; creates an array with 10 slots. You can do both steps at once: int[] ports = new int[10];
When you create an array, Java automatically fills all the empty slots with default values. For integers, that default is 0. For text strings (the String type), the default is null, which means "no value yet". For booleans, the default is false.
Putting data into an array and reading it back
Each slot in an array has a position number called an index, and Java always starts counting from 0. In an array of 10 items, the first item is at index 0, the second is at index 1, and the last is at index 9. To put a value into a specific slot, write the array name, the index in square brackets, an equals sign, and the value: ports[0] = 8080; puts the number 8080 into the first slot.
To read a value back out, use the same notation: int myPort = ports[0]; copies the value from the first slot into a new variable called myPort. You can also use an array value directly in calculations or print statements without copying it first: System.out.println(ports[0]); prints whatever is in the first slot.
If you try to access an index that does not exist — for example, ports[15] when your array only has 10 slots — Java stops your program and throws an ArrayIndexOutOfBoundsException error. Always make sure your index is between 0 and one less than the array size.
Creating arrays with initial values
Instead of creating an empty array and filling it slot by slot, you can create an array and load it with values all at once. Use curly braces and list the values separated by commas: int[] ports = {8080, 8443, 3306, 5432}; creates an array with 4 slots and fills them with those four port numbers in order. Java counts the values and sets the array size automatically.
This shorthand works with any data type. For text strings: String[] servers = {"192.168.1.1", "192.168.1.2", "192.168.1.3"}; creates an array of three IP addresses. For booleans: boolean[] active = {true, false, true}; creates an array of three true/false values. The values must match the declared type — you cannot mix integers and text strings in the same array.
Working with arrays in loops
The real power of arrays shows up when you use them with loops. A for loop lets you do the same action to every item in an array without writing the code over and over. The most common pattern is: for (int i = 0; i < ports.length; i++) { System.out.println(ports[i]); } This loop starts at index 0, prints each value, and stops when it reaches the end. The ports.length property tells you how many slots the array has, so the loop never tries to access an index that does not exist.
Java also offers an enhanced for loop (sometimes called a "for-each" loop) that is simpler when you just need to visit every item: for (int port : ports) { System.out.println(port); } This reads as "for each port in ports, print it". You do not need to manage the index yourself — Java handles it automatically. This style is cleaner when you do not need to know which position you are at, only what the value is.
Arrays of objects and multi-dimensional arrays
Arrays can hold objects, not just simple numbers and text. If you have created a class called NetworkDevice, you can create an array of those objects: NetworkDevice[] devices = new NetworkDevice[5]; This creates 5 empty slots, each ready to hold a NetworkDevice object. You then fill each slot by creating objects and assigning them: devices[0] = new NetworkDevice("Router", "192.168.1.1");
Java also supports multi-dimensional arrays, which are arrays of arrays. A two-dimensional array is useful for grids or tables of data. Declare it with two sets of brackets: int[][] grid = new int[3][4]; creates a grid with 3 rows and 4 columns. Access items with two indices: grid[0][1] means row 0, column 1. Multi-dimensional arrays are less common in everyday code but appear in network topology maps, traffic matrices, and similar structured data.
Common mistakes and how to avoid them
The most frequent error is forgetting the new keyword. Writing int[] numbers; declares the array variable but does not create it. If you then try to put a value in it, Java throws a NullPointerException because the variable points to nothing. Always use new to actually build the array: int[] numbers = new int[5];
Another common mistake is confusing the array size with the highest valid index. An array of size 5 has indices 0, 1, 2, 3, and 4 — not 1 through 5. Trying to access numbers[5] crashes the program. When writing loops, use i < array.length (less than), not i <= array.length (less than or equal to).
A third pitfall is trying to change an array's size after creating it. Arrays have a fixed size; you cannot add or remove slots. If you need a container that grows and shrinks, use an ArrayList instead, which is a more flexible alternative. For now, plan your array size carefully before you create it.
Frequently Asked Questions
Can I create an array without knowing the size ahead of time?
No, arrays require a fixed size when you create them. If you do not know the size in advance, use an ArrayList instead — it grows automatically as you add items. You can convert an ArrayList to an array later if you need to.
What happens if I declare an array but never use all the slots?
That is fine. If you create an array of 10 integers but only fill 5 of them, the other 5 stay at their default value (0 for integers). The unused slots still take up memory, but there is no error or penalty for leaving them empty.
Can I store different types of data in the same array?
No, all items in an array must be the same type. An integer array holds only integers, a string array holds only strings. If you need to mix types, create an array of Object (the parent type of all Java objects), but then you have to cast each item back to its real type when you use it, which is awkward.
How do I copy an array to a new variable?
Simply assigning one array to another does not copy it — it just makes both variables point to the same array. Use System.arraycopy() or the Arrays.copyOf() method to create a true copy. For example: int[] copy = Arrays.copyOf(original, original.length);
Can I print an entire array with one command?
Printing an array directly with System.out.println(array) shows a memory address, not the values. Use System.out.println(Arrays.toString(array)); to see the contents in a readable format, or loop through and print each item individually.