The Java Tutorial: Arrays
We've already covered primitive data types in Java. It's now time to look at the Array object.
What is an array in Java?
An array is a container object. It holds a fixed number of values of a single type. An array's size is set when it's' initialized. An array's size does not change.
Basic example of an array in Java
public class MyClass {
public static void main(String args[]) {
char[] myArray = new char[5];
myArray[0] = 'a';
myArray[1] = 'b';
myArray[2] = 'c';
myArray[3] = 'd';
myArray[4] = 'e';
System.out.println(myArray[3]);
//prints d
}
}
Creating Arrays
In this example, we've set a variable myArray to a new array with 5 char elements. Notice how we specify both the type of element char and size [5]. This means our myArray array will hold 5 elements of the char data type.
As an alternative, we could have initialized the same array like this:
char[] myArray = {'a', 'b', 'c', 'd', 'e'};
Assigning elements to an array
In the first example, notice how we set the first element in myArray.
myArray[0] = 'a';
This assigns a value 'a' to the first element in the array. Elements in an array are stored in a specific order. This means each element has a corresponding index position that you can access it by. Notice how we access the 4th element in the array:
myArray[3]
//returns the 4th element in the array
This reads the element at position 3 (or the 4th element) in the array, in this case 'd'.
Why is the first element 0 and not 1?
To access the first element in an array, we start at position 0. This means the second element is at position 1, the third at position 2, etc. This is called zero-based indexing meaning the position is simply an offset from the beginning of the array.
Multidimensional arrays in Java
You can create arrays of arrays in Java...
public class MyClass {
public static void main(String args[]) {
char[][] myArray = {
{'a','b','c','d'},
{'e','f','g'}
};
System.out.println(myArray[1][2]);
//prints g
}
}
Notice how we add an additional [] to signify a multidimensional array. We access a specific element in the array via myArray[1][2]. This returns the third element of the second element of myArray.
Using the java.util.Arrays class
Java provides some methods out of the box for working with arrays. Using the java.utils.Arrays class, you can perform searches, sorting, copying, etc. of arrays. The following are examples of using some of the most popular methods in java.utils.Arrays:
Copy an array
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
char[] myArray = {'a','b','c','d'};
char[] copyArray = Arrays.copyOfRange(myArray, 1, 3);
System.out.println(copyArray);
//prints bc
}
}
Notice how we make use of the Arrays.copyOfRange() method to return a copy of the original myArray array. You'll notice this method takes three parameters. The first parameter is the source array, in this case myArray. The second parameter is the initial index of the range to be copied (inclusive), in this case 'b'. The third parameter is the final index of the range to be copied (exclusive).
inclusive vs exclusive
Given the range 1-5 inclusive, we get (1,2,3,4,5). Given the same range exclusive, we get (1,2,3,4). In our previous example, the copyOfRange() method accepts an exclusive position as its third parameter.
The System class has a similar arraycopy() method however the Arrays.copyOfRange() is generally preferred because it doesn't require the preexistence of a second array and simply returns the copied result.
Search an array
Using binary search, you can search an array for a specific value. For example:
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
char[] myArray = {'a','b','c','d'};
int position = Arrays.binarySearch(myArray, 'c');
System.out.println(position);
//prints 2
}
}
In this example, we use the Arrays.binarySearch() method to search myArray for the value 'c'. Notice how the method returns an integer being the position of the first occurrence of 'c' in myArray.
This method optionally supports another parameter specifying an end index. This allows you to search for a value within a given range.
Compare array equality
Two arrays are considered equal if they contain the same elements in the same order.
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
char[] array1 = {'a','b','c','d'};
char[] array2 = {'a','b','c','d'};
char[] array3 = {'a','c','d','b'};
System.out.println(Arrays.equals(array1, array2));
//prints true
System.out.println(Arrays.equals(array1, array3));
//prints false
}
}
Notice how we use the Arrays.equals() method to see if any two given arrays are equal. Remember that arrays are equal if they contain the same number of elements in the same order. Although array1 and array3 have the same length, they don't have the same elements. For this reason, they are not considered equal. Since array1 and array2 have the same elements in the same order, they are equal.
Sorting an array
You can sort an array of integers using the Arrays.sort() method:
import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {
int[] myArray = {33,55,23,64,2};
Arrays.sort(myArray);
System.out.println(myArray[0]);
//prints 2
}
}
Notice how we call Arrays.sort() to sort myArray in ascending order. After calling the sort method on myArray, the first element at position 0 is now 2.
The Arrays.sort() method can also be used to sort strings in alphabetical order, sort sub arrays, and sort based on custom logic.
Conclusion
Java arrays are collections of elements having the same type. An array's size is fixed when it's initialized. Arrays are good for storing collections of elements where order matters. Every element stored in an array has a corresponding index. You can access and modify an array's elements based on their position within the array.