In this article, we will explain what an array is in Java, how it works, and when it should be used. Every section will include code examples in order to understand the most important aspects of Java arrays.
1. What is a Java Array?
An array is a fixed-length object which contains one or more elements of the same type.
In order to visualize an array, below is a diagram of how a String
array with length 6 would look like.
![Array Visualization](https://youlearncode.com/wp-content/uploads/2022/10/String-Array.webp)
1.1 Most important characteristics of Java arrays
- Arrays extend the Object class
- Arrays are fixed-length; you cannot resize an array like you would when using a List.
- The type of an array could be a primitive or an Object type
- Arrays can be of multiple dimensions (2-d, 3-d, etc.) but it’s unlikely that you’ll need more than 2 dimensions
- After declaration, if the array is of primitive type, every cell will have the default value (e.g. for int is 0).
- After declaration, if the array is of Object type, every cell will have
null
value. - Arrays are immutable, which means that you cannot change anything other than the value inside each cell.
- Every array has a length attribute, which can be used to get the number of rows of an array if it is 2 or more dimensions, otherwise, the total length of the array.
2. One-dimensional array in Java
In this section, we’ll go through all the operations when dealing with 1-d arrays.
A one-dimensional array is the most commonly used array, we already visualized how it would look like, in section 1. To retrieve the length of an array in java the syntax is the following:
array_name.length;
2.1 How to initialize an array in Java
To create a one-dimension array in Java, the formula is the following:
Object_type_or_primitive[] array_name = new Object_type_or_primitive[int_or_short_value]
For example, we could initialize an array of type Person and length 3, with the following command:
Person[] persons = new Person[3];
In addition, we could use primitive types, so to create an array of type short
and length 100, the command is the following:
short[] numbers = new short[100];
Should you like to declare and initialize an array in one command, you could use the following formula:
Object_type_or_primitive[] array_name = { value_1, value_2, value_3, ..., value_n}
So, to initialize the array in section 1, the command is the following:
String[] names = {"Akis", "Giorgos", "Nikos", "Dimitris", "Giannis", "Kostas"};
2.2 Accessing an array
To access an array, the formula is the following:
Object_type_or_primitive element = array_name[index]
To access the 151st of an array with the following attributes:
- Length is 200
- Type is
ArrayList<String>
- Name is lists
You would write the following:
ArrayList<String> list = lists[150];
2.3 Traversing an array
To traverse an array, you’ll need to use a for loop. There are 2 ways to do this:
2.3.1 Using a simple for loop
The formula to traverse the whole array by using a simple for loop is the following:
for (int i = 0; i < array_name.length; i++) { //Actions }
2.3.1 Using an enhanced for loop
The formula to traverse the whole array by using an enhanced for loop is the following:
for (Object_type_or_primitve local_variable_name : array_name) { // Actions }
Note that if you use this type of loop, you will not have the index as information inside the loop, therefore, you will be unable to modify an element.
2.4 Array manipulations
2.4.1 Modify an entry at a specific index
To modify an array, the only thing you’ll need to do is to assign an element with a different value. The formula is the following:
array_name[index] = new_value
Let’s say we have an array with the following attributes:
- The length is 25
- The type is int
- The name is numbers
To set the 23rd element to have the value 10, you would write the following:
numbers[22] = 10;
2.4.2 Deleting an element at a specific index
Unfortunately, it is not possible to completely delete an element without copying the array into a new array.
The closest thing to deleting an element is to set the entry to a null
value (this cannot be done for arrays with primitive types).
Should you really require to delete an entry, there are some workarounds but are time-expensive so they are not suggested to be used. If you know that the data structure that you’ll use might need deletions, it’s preferable to use lists.
Below, you can find an example of how you could delete an element of an array
public class DeleteElementFromArray { public static void main(String[] args) { String [] names = new String [] {"Akis", "Giorgos", "Nikos", "Giannis"}; System.out.println("Array before any action:"); printArray(names); // Delete at index 2 names = deleteElement(names,2); System.out.println("Array after deletion of index 2:"); printArray(names); // Delete at index 2 again names = deleteElement(names,5); System.out.println("Array after deletion of index 2:"); printArray(names); } public static String[] deleteElement( String[] array, int index){ if( index<0 || index >= array.length) throw new IllegalArgumentException("Index given is incorrect"); //To completely delete an element from an array, // you can create a new array with size // equal to the array given minus 1 (since it will contain one less element) String [] arrayCopy = new String[array.length-1]; // Then traverse through the old array and copy only the wanted elements for (int i = 0,j = 0; i < array.length ; i++,j++) { //If i equals the index of deletion, // do not assign a value, // and subtract the index of copyArray // so the two indices match // (i and j) if(i == index){ j--; } // This element should be copies, as we do not want to delete it else { arrayCopy[j] = array[i]; } } return arrayCopy; } public static void printArray(String[] array){ for (int i = 0; i <array.length ; i++) System.out.println("Index : " + i + ", Element: "+array[i]); System.out.println(); } }
The output is:
Array before any action: Index : 0, Element: Akis Index : 1, Element: Giorgos Index : 2, Element: Nikos Index : 3, Element: Giannis Array after deletion of index 2: Index : 0, Element: Akis Index : 1, Element: Giorgos Index : 2, Element: Giannis Array after deletion of index 2: Index : 0, Element: Akis Index : 1, Element: Giorgos
Let’s explain the deleteElement()
method:
- In line 26, we check if the index parameter given is correct, since we do not want an
ArrayIndexOutOfBoundsException
. If it is correct we proceed, otherwise, we throw aIllegalArgumentException
with the appropriate message. - In line 29, we create a new array, with size one less than the original array, since we’ll delete an element.
- In line 39, if we have the index that should be deleted, we do nothing and reduce the index of copyArray, so as the array and copyArray indices match
- In line 44, for every element that we do not want to delete, we copy the value to the new array.
- In line 47, we return the array after deletion.
3. 2d Array in Java
You can imagine two-dimensional arrays, as multiple one-dimensional arrays, stacked next to each other. An example of a two-dimensional array in real life is a chessboard. A 2d array would look like this:
![2d array visuzalization](https://youlearncode.com/wp-content/uploads/2022/10/Screenshot_6.png)
3.1 How to initialize a 2d array in Java
To initialize a 2d array, the formula is the following:
Object_type_or_primitive[][] array_name = new Object_type_or_primitive[int_or_short_value_rows] [int_or_short_value_columns]
For example, we could initialize an array of type String
with 3 rows and 3 columns, with the following command:
Person[][] persons = new Person[3][3];
Should you like to declare and initialize a java array in one command, you could use the following formula:
Object_type_or_primitive[][] array_name = { {value_1,value_2}, {value_3,value_4}, ... , {value_n,value_m}}
So, to create a 3 X 3 with Xs and Os (like tic-tac-toe), we would write the following:
String[][] names = { {"X", "X", "X"}, {"O", "X", "O"}, {"O", "X", "O"} };
3.2 Accessing a 2d array
To access a 2d array, the formula is the following:
Object_type_or_primitive element = array_name[row_index][column_index]
To access the element in [4,9] of an array with the following attributes:
- The size is 5 X 10
- The type is
int
- The name is numbers
You would write the following:
int number = numbers[4][9];
3.3 Traversing a 2d array
To iterate a 2d array, you’ll need to use a for loop. There are 2 ways to do this:
3.3.1 Using a simple for loop
We usually set the rows number and column number as a constant variable and then use them inside the loop. The formula to traverse the whole array by using a simple for loop is the following:
for (int i = 0; i < ROWS ; i++) { for(int j = 0; j < COLUMNS; j++){ //Actions } }
3.3.2 Using an enhanced for loop
The formula to traverse the whole array by using an enhanced for loop is the following:
for( Object_or_primitive_type[] row : array_name){ for(Object_or_primitive_type element : row){ //Actions } }
Note that if you use this type of loop, you will not have the row and column indices as information inside the loop, therefore, you will be unable to modify an element.
3.4 Modify an entry at a specific row and column index
To modify a 2-d array, the only thing you’ll need to do is to assign an element with a different value. The formula is the following:
array_name[row_index][column_index] = new_value
Let’s say we have an array with the following attributes:
- The size is 4 X 5
- The type is
String
- The name is countries
To set the [3, 2] element to have the value 10, you would write the following:
numbers[3][2] = "Greece";
4. Java Array of 3 or more dimensions
It is unlikely that you’ll ever need to use a 3d array, let alone a 4d or a 5d array. But, to cover everything, in this section we’ll go through how a 3d array would look like and how to instantiate one.
You can image a 3d array, as an array that contains multiple 2d arrays. So a 3d array would look like this:
![3d array visualization](https://youlearncode.com/wp-content/uploads/2022/10/3-d-array.webp)
Should you want to traverse a 3d array, you’d need to perform 3 loops, each nested into each other, like this:
for(int i = 0; i < TABLES; i++) { for(int j = 0; j < ROWS; j++) { for(int k = 0; k < COLUMNS; k++) { System.out.println(numbers[i][j][k]); } } }
For more dimensions, the logic is the same. For example, a 4-d array would be something like a 2-d array that each element is a 2-d array.
So, to access a 4-d array you’d need to provide the 4 values:
- The row index of the “big” array
- The column index of the “big” array
- The row index of the “small” array
- The column index of the “small” array
5. Questions about arrays in Java
5.1 How to return an array in Java?
To return an array in Java you just return the name of a variable, consider the example below:
private static int[] addOneAndReturn(int[] array){ for (int i = 0; i < array.length; i++) { array[i]++; } return array; }
This is a very simple demonstration of how you could return an array in Java. We just added 1 to every element of the array and returned it by just typing return and the name of the variable that points to that array.
5.2 How to print an array in Java?
There are many ways to print an array, The first but not the most efficient is to loop through all elements and then print the value of each element, as shown below:
private static void printArray(int[] numbers){ for(int i : numbers){ System.out.print(i+" "); } }
But as you can notice, this will get more complicated the more dimensions you have, but the big advantage of this is that you can format it in any way you like.
However, there is an easy way, you just have to call the method Arrays.toString(your_array_name)
and it will return the array in the following format:
[element_1, element_2, ..., element_n]
An important note here is that if your array contains custom objects, you have to override the toString() method in order to get the expected results.
5.3 How to sort an array in Java?
This question has the easiest answer. You just have to call the void method Arrays.sort()
as shown below:
Arrays.sort(array_name)
As before, if your array contains custom objects you have to implement the Comparable
interface or create a Comparator
class in order for Arrays.sort()
to work as expected.
6. Conclusion
By now, you should have understood what an array is in Java, how it works, and be able to use arrays more efficiently. You can find the source code on our GitHub page.
7. Sources
[1] : Arrays – Oracle