In this section we will learn what the Arrays are and how to use them in Java.
What Is Array in Java?
When we want to store a range of values in one variable, we can use arrays.
For example, let’s say we have 10 integer elements and we want to store them.
Instead of creating 10 different variables and store these elements in each variable, we can create an array of type integer and store all the elements in that variable.
The way we access these values is a little bit different than the usual way of accessing values in simple variables but before we get into those details, first let’s see the structure of an array.
Declaration of Array in Java
Data-type [] array-name;
`data-type` of arrays: here we set the data type of the values that are going to be stored in the array.
Note: all the values should be of the same data type.
`array-name`: just like other variables, an array should have name as well.
Note: all the rules that apply to name of a variable, also apply to the name of an array variable.
`[]`: We need to use the pair of brackets between the data-type and the array-name or after the array-name and this signals the compiler that the variable is actually an array variable.
So far we’ve just declared a variable as an array. But now if we want to store values in that array, we have two options:
- Direct initialization
- Declaration first and initialization later.
Initialize an Array in Java: Single Dimensional Array (Array Literal)
An array that is directly initialized with values right where the declaration is done is known as array literal. We can use the assignment `=` operator and after that via a pair of braces `{}` we can store the values in the array.
Example: creating array literal in Java
int []iArray = {1,2,3,4,5,6};
Notes:
- In the braces we use comma `,` to separate values from each other.
- The size of the array in this case is automatically declared and it is equal to the number of elements we set for the array. For example if we initialized an array with 6 elements, then that array has the length of 6.
- The size of an array is static and that means after we or the compiler declared the size of that array, we can’t store more values than the size in that array.
Declaring an Array in Java
When creating an array, we might not have the values right away to store in that array. So in such case we can set the size of that array (with the help of the `new` keyword) and later in the program, store elements in that array.
Creating an array via the `new` keyword:
Data-type [] array-name = new Data-type [number-of-elements];
As you can see, after the `array-name` we use the assignment `=` operator and after that comes the `new` keyword; followed by that comes the name of the `data-type` which should be the same as the data-type of the `array-name` and finally the brackets.
` number-of-elements`: This is where we declare the number of elements that we want this array to be able to store. For example, if we want the target array be able to store 100 elements, we can set the value 100 in the brackets.
Example: declaring an array in Java
int []iArray = new int[100];
Access and Change the Elements of an Array in Java
Arrays have index number and it starts from 0. We use the index number to reach the target element in the array in order to retrieve or assign a value in that index.
This is how we use index numbers in arrays:
Array-name[index-number]
`array-name`: this is the name of the target array.
`[]`: after the name of an array, comes the brackets and within the brackets we set the index number.
Note: because the first item in an array is at index 0, the final item in that array will be at index `arraySizse -1`.
For example, let’s say an array has 10 items; the first element in that array is at index 0 and the final element will be at index number 9.
Example: Accessing and Changing Java Array Elements
public class Simple { public static void main(String[] args) { int age[] = new int[10]; age[0] = 10; age[1] = 20; age[2] = 30; age[3] = 40; age[4] = 50; age[5] = 60; age[6] = 70; age[7] = 80; age[8] = 90; age[9] = 100; System.out.println("The value at index 4 is: "+age[4]); } }
Output:
The value at index 4 is: 50
As you can see, in order to assign a value to an element of the `age` array, we put the array’s name and brackets on the left side of the assignment `=` operator and the target value on the right side. This will replace the value that is already in that index (if any) with the new value.
Also calling the array with brackets and index number in other places (other than being used as Lvalues or on the left side of an assignment operator) will return the value that is stored in the target index. This is what we did when called `age[4]` in the `println()` method.
Types of arrays in Java:
– Java Single Dimensional Array
– Java Multidimensional Array
Array Length in Java
In later sections we will introduce what objects are, but for now just remember that when we create an array, we’re actually creating an object.
This object has different methods and properties that can be used.
One useful property of an array that can be used, is `length`.
Via this property we can get the number of elements that can be stored in a particular array.
Example: getting the length of an array in Java
public class Simple { public static void main(String[] args) { int age[] = new int[10]; for (int i = 0; i<age.length; i++){ age[i] = i; } for (int i : age){ System.out.print(i+", "); } } }
Output: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
To use the `length` property, we put dot `.` after the name of that array like `age.length` and this will return the length of that array.
In this example we’ve created a `for` loop to go through all the index of an array and store a value in each of those indices.
After that via `for each` loop, we went through the indices of the array and printed all the elements to the screen.
Java final Array
An array can be final as well.
When an array is final, that means the array variable can’t point to another array. But it can modify its content for as many times as needed in the program.
Example: creating final array in Java
public class Simple { public static void main(String[] args) { int [] array = new int[30]; final int range[] = {1,2,3,4,5,6,4}; range[0] = 10; range[2] = 100; range[0] = 1000; //Error because we can't assign another array to a final array-variable. range = array; } }
Passing Arrays to Methods in Java
Arrays can be passed as the arguments to methods as well!
You should know that when we pass an array as the argument to another method, only the memory address of the target array will be passed to the target array!
This means both the parameter of the method as well as the variable of the array are pointing to the same array. So if one of them changed the content of the target array, the other will see the change.
Note: please check the pass by reference and value section in order to learn more about this topic.
Example: passing arrays to methods in Java
class Main{ public static void main(String[] args) { int [] array = { 1,2,3,4,5,6,7,8,9,10 }; secondMethod(array); System.out.println(array[0]); } public static void secondMethod(int[] arr){ arr[0]=1000; } }
Output:
1000
In this example the `secondMethod` has one parameter and it takes an array of type integer. After that it will change the first element of this array to 1000 inside the body of this method.
Now in the body of the `main` method, we’ve created an array-literal called `array` and passed this variable as the argument of the `secondMethod()`. So here here the memory address of the location in the memory that the array is stored is passed to the `arr` parameter of the `secondMethod`. This means now the `arr` as well as the `array` variables are pointing to the same memory location.
That’s why when the `arr` parameter changed the first element of the target array, the `array` variable saw this change when calling it in the `println()` method to take the first element of the array.
Returning an Array from a Method in Java
Other than passing an array to a method we can also return an array from a method as well!
For this to happen we need to set the return data type of the target method to an array of the same type as the elements of the array we want to return.
Note: again you should know that arrays are stored in the memory and variables only get the memory address of the target array. That means when returning an array from a method, only the memory address of the array is returned and the array itself will stay in the memory. So no copy of that array will return! Just the memory address.
Example: returning an array from a method in Java
class Main{ public static void main(String[] args) { int[]array = getArray(); System.out.println(array[0]); } public static int[] getArray(){ int [] array = { 1,2,3,4,5,6,7,8,9,10 }; return array; } }
Output:
1
Anonymous Array in Java
Anonymous arrays are those that we create on the fly without storing them in a variable and usually pass them as the argument to a method etc.
For example, you might have a method that needs an array of integer values! But you don’t have an array variable to pass to the method! So in situation like this, we can create an anonymous array directly in the parentheses of the method where it is being called.
Java Anonymous Array Syntax:
new data-type[]{value1,value2,value3,valueN}
Example: creating anonymous array in Java
class Main{ public static void main(String[] args) { needArray(new int[]{1,2,3,4,5,6,7,8}); } public static void needArray(int [] array){ System.out.println(array[3]); } }
Output:
4
In the `main` method we’ve called the `newArray()` method. This method needed an array but we hadn’t one! So we’ve created an anonymous array and passed that as the argument to the method.
That means now the `array` variable contains a reference to this anonymous array. That’s why we could access the third index of the array.
Java ArrayIndexOutOfBoundsException
When working with arrays, you need to be careful not to cause an error!
One of these errors is the ArrayIndexOutOfBoundsException!
We get this error if we try to access an index of an array that the array doesn’t have!
For example, an array might have only 10 elements, but we call the index number 130 of that array! Now because there’s no such index for this array, Java will return the mentioned error instead!
Note: how to handle errors is covered in the Java try-catch section.
Example: throwing ArrayIndexOutOfBoundException
class Main{ public static void main(String[] args) { int [] array = {1,2,3,4,5}; System.out.println(array[130]); } }
Output:
java.lang.ArrayIndexOutOfBoundsException: Index 130 out of bounds for length 5
at Main.main(Main.java:4)
As you can see, this array only has 5 elements but we’ve called for the index number 130! That’s why we got the ArrayIndexOutOfBoundsException.
Example: creating String Array in Java
class Main{ public static void main(String[] args) { String [] array = {"Omid","Ellen","Ian","Elon"}; System.out.println(array[1]); } }
Output: Ellen
Java Print Array: How to Print an Array in Java
If we want to print the entire elements of an array, we can use either of loops that Java provided like for-each loop, for-loop, while-loop etc.
In the section below we’ve covered how to iterate through the elements of an array in order to do the necessary tasks including printing them on the console.
Java Array and for loop
Arrays are iterable! That means we can use loops like `for` loop or `for-each` etc. to loop through the elements of arrays and run the necessary tasks on each element.
In case of `for` loop, we need to use the length of the target array (its size basically) using the `length` property of an array if the purpose is to loop through the entire elements of an array.
Example: using for loop to iterate an array
class Main{ public static void main(String[] args) { int [] array = {1,2,3,4,5,6,7,8,9,10}; for (int i = 0; i<array.length; i++){ System.out.print(array[i]+", "); } } }
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Java Array for-each Loop:
Another way and perhaps an easier way to loop through the entire elements of an array is to use the Java `for-each` loop! This loop by default will iterate through the entire elements of an array and so there’s no need for calling the `length` property of the target array!
Example: using for-each loop to iterate an array
class Main{ public static void main(String[] args) { int [] array = {1,2,3,4,5,6,7,8,9,10}; for (int element : array){ System.out.print(element+", "); } } }
Output:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
Example: creating an array of integers in Java
class Main{ public static void main(String[] args) { int [] array = {1,2,3,4,5,6,7,8,9,10}; System.out.println(array[5]); } }
Output:
6