Java Arrays class tutorial with examples will help you understand how to use the Java Arrays class in an easy way. The Arrays class in Java is a utility class provided by Java to manipulate arrays.
The Arrays class contains various utility methods to sort the array, search the array and fill the array with specified elements. The Arrays class also provides methods for copying an array to another array and converting an array to a List.
The Arrays class in Java is contained in the java.util package, so you have to import java.util.Arrays
to use it in the code. The Arrays class is a part of the Java Collection Framework.
How to convert an array to String using the toString method?
The toString
method returns a string representation of the specified array.
If the array elements are of primitive types, they are converted to the String using the valueOf
method of the String class. If the array elements are objects, they are converted to String using the toString
method. Each individual array elements are separated by “, ” (a comma followed by a space) and the whole string is enclosed in square brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
int[] intArray = {1, 2, 3, 4, 5}; /* * To convert an array to String, use the * toString method. * * The array elements are converted to String * using the String.valueOf(int i) method. */ //this will print[1, 2, 3, 4, 5] System.out.println(Arrays.toString( intArray )); String[] strArray = {"a", "b", "c"}; /* * In case of an object type, the array elements are converted to String * using the toString method. */ //this will print[a, b, c] System.out.println(Arrays.toString( strArray )); |
Output
1 2 |
[1, 2, 3, 4, 5] [a, b, c] |
How to sort an array using the sort method?
The static sort
method allows an array to be sorted in ascending order, descending order or using a custom Comparator object. The default order of sorting is ascending order, however, you can also specify custom Comparator object to suit your needs. The below given sort
method is overloaded to accept byte, short, char, int, long, float, double, and Object types.
1 |
public static void sort(int[] intArray) |
For this example, we are going to sort an int array, but you can sort an array of any type mentioned above.
1 2 3 4 5 6 7 8 9 10 11 |
//int array int[] intArray = {3,4,2,1,5}; System.out.println("int array elements: " + Arrays.toString(intArray)); /* * To sort an int array in ascending order, use the * sort method of the Arrays class */ Arrays.sort(intArray); System.out.println("sorted int array elements: " + Arrays.toString(intArray)); |
Output
1 2 |
int array elements: [3, 4, 2, 1, 5] sorted int array elements: [1, 2, 3, 4, 5] |
How to sort a partial array using the sort method?
If you want to sort a partial array, you can use the overloaded version of the sort
method having startIndex and endIndex parameters.
1 |
public static sort(int[] intArray, int startIndex, intEndIndex) |
This method sorts the specified range of the array in ascending order. Here, the startIndex is inclusive while the endIndex is exclusive. This method throws ArrayIndexOutOfBoundsException if the startIndex is less than 0 or endIndex is greater than the array length.
1 2 3 4 5 6 7 8 9 10 11 12 |
//int array int[] intArray = {3,4,2,1,5}; System.out.println("int array elements: " + Arrays.toString(intArray)); /* * To sort a partial int array in ascending order, use the * sort method of the Arrays class and specify the start and end index. */ //this will sort array elements 4, 2, and 1 in ascending order Arrays.sort(intArray, 1, 4); System.out.println("partially sorted int array elements: " + Arrays.toString(intArray)); |
Output
1 2 |
int array elements: [3, 4, 2, 1, 5] partially sorted int array elements: [3, 1, 2, 4, 5] |
This method is also overloaded for byte, short, char, int, long, float, double, and Object types.
How to sort an array of custom objects using a Comparator using the sort method?
The below given overloaded sort
method sorts an array of objects according to the order defined by the specified Comparator object.
1 |
public static <T> void sort(T[] a, Comparator<? super T> comparator) |
The below given example sorts an array of custom objects in ascending and descending orders using the respective comparator objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
class Student{ private int id; private String name; public Student(int id, String name){ this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } //for printing purpose public String toString(){ return "(" + getId() + " => " + getName() + ")"; } } //this comparator will sort Student objects in ascending order by id class StudentComparator implements Comparator<Student>{ public int compare(Student s1, Student s2) { return s1.getId() - s2.getId(); } } //this comparator will sort Student objects in descending order by id class StudentDescendingComparator implements Comparator<Student>{ public int compare(Student s1, Student s2) { return s2.getId() - s1.getId(); } } public class Example { public static void main(String[] args) { Student[] studentArray = { new Student(3, "Jack"), new Student(1, "Ryan"), new Student(2, "Adam") }; System.out.println("object array before sorting: "); System.out.println( Arrays.toString(studentArray) ); /* * To sort an object array by custom comparator, use * the sort method and specify the comparator object */ //sort Student objects in the ascending order using the StudentComparator Arrays.sort(studentArray, new StudentComparator()); System.out.println("object array after sorting in ascending order by id: "); System.out.println( Arrays.toString(studentArray) ); /* * Similarly, sort an array of objects in descending order * using the sort method */ //this will sort Student objects in the descending order using the StudentDescendingComparator Arrays.sort(studentArray, new StudentDescendingComparator()); System.out.println("object array after sorting in descending order by id: "); System.out.println( Arrays.toString(studentArray) ); } } |
Output
1 2 3 4 5 6 |
object array before sorting: [(3 => Jack), (1 => Ryan), (2 => Adam)] object array after sorting in ascending order by id: [(1 => Ryan), (2 => Adam), (3 => Jack)] object array after sorting in descending order by id: [(3 => Jack), (2 => Adam), (1 => Ryan)] |
You can also use an overloaded sort
method with the startIndex and endIndex parameters to sort the partial object array. The startIndex is inclusive, while the endIndex is exclusive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
class Student{ private int id; private String name; public Student(int id, String name){ this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } //for printing purpose public String toString(){ return "(" + getId() + " => " + getName() + ")"; } } //this comparator will sort Student objects in ascending order or id class StudentComparator implements Comparator<Student>{ public int compare(Student s1, Student s2) { return s1.getId() - s2.getId(); } } public class Example { public static void main(String[] args) { Student[] studentArray = new Student[5]; studentArray[0] = new Student(3, "Jack"); studentArray[1] = new Student(1, "Ryan"); studentArray[2] = new Student(5, "Jay"); studentArray[3] = new Student(2, "Adam"); studentArray[4] = new Student(4, "Mike"); System.out.println("object array before sorting: "); System.out.println( Arrays.toString(studentArray) ); /* * To sort partial object array using the comparator, use the * sort method and specify an array to sort, start index, end index * and a comparator object */ Arrays.sort(studentArray, 0, 4, new StudentComparator()); System.out.println("object array after partial sorting: "); System.out.println( Arrays.toString(studentArray) ); } } |
Output
1 2 3 4 |
object array before sorting: [(3 => Jack), (1 => Ryan), (5 => Jay), (2 => Adam), (4 => Mike)] object array after partial sorting: [(1 => Ryan), (2 => Adam), (3 => Jack), (5 => Jay), (4 => Mike)] |
As you can see from the output, the Student object array is partially sorted. The array elements at index 0, 1, 2, and 3 are sorted while the element at index 4 (the last element) remains as is.
How to convert an array to List using the asList method?
The static asList
method returns a fixed-size list that is backed by the original array.
1 2 3 4 5 |
String[] strColors = {"Red", "Green", "Blue"}; //convert array to List List<String> listColors = Arrays.asList(strColors); System.out.println( listColors ); |
Output
1 |
[Red, Green, Blue] |
Please note that the list returned by asList
method is backed by the original array. Any modification done to the original array is also reflected back to the list.
1 2 |
strColors[1] = "Yellow"; System.out.println( listColors ); |
Output
1 |
[Red, Yellow, Blue] |
How to search an element in an array using the binarySearch method?
The static binarySearch
method allows us to search an element in an array using the binary search algorithm. The binarySearch
method is overloaded for byte, short, char, int, long, float, double, and Object types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
//string array String[] strArray = {"Jay", "Ray", "Steve", "Adam", "Zoey", "Chris"}; /* * The binarySearch method expects the array to be sorted. * if it is not sorted, the results are undefined. * * Sort string array using the sort method */ Arrays.sort(strArray); System.out.println("Sorted String Array contains: " + Arrays.toString(strArray)); /* * Search an element in an array using the binarySearch method. */ System.out.println( "Index of Chirs in an array: " + Arrays.binarySearch(strArray, "Chris") ); |
Output
1 2 |
Sorted String Array contains: [Adam, Chris, Jay, Ray, Steve, Zoey] Index of Chirs in an array: 1 |
Important: The array must be sorted for the binarySearch
method to work. It the array is not sorted, the result of this method call is undefined.
If the element is found, the binarySearch
method returns an index of the element in the array. If the element is not found, the binarySearch
method returns (-(insertion point) – 1) where the insertion point is an index of the first element greater than the key or the length of the array, if all array elements are less than the specified element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
//string array String[] strArray = {"Jay", "Ray", "Steve", "Adam", "Zoey", "Chris"}; //sort the array Arrays.sort(strArray); System.out.println("Sorted String Array contains: " + Arrays.toString(strArray)); /* * This will return -1. The element Aakash would have been * inserted at index 0 in the array since its lower than all * the existing elements. So the return value will be * (-(0) - 1) = -1 */ System.out.println(Arrays.binarySearch(strArray, "Aakash")); /* * This will return -7. Since all the elements of the array * are less than the element "Zoo", it would have been inserted at * the last index. So the return value will be * (-(6) - 1) = 7 */ System.out.println(Arrays.binarySearch(strArray, "Zoo")); |
Output
1 2 3 |
Index of Chirs in array: 1 -1 -7 |
You can also search a partial array using the overloaded binarySearch
method having start and end index parameters.
1 |
static int binarySearch(int[] array, int startIndex, int endIndex, int element) |
Here, the startIndex is inclusive while the endIndex is exclusive.
How to fill an array with the specified element using the fill method?
The static fill
method allows us to fill an array with the specified element. The fill
method fills all the elements of an array with the given value. The fill
method is also overloaded to accept all primitive type arrays and objects.
1 2 3 4 5 6 |
int[] intArray = new int[5]; //assigns 999 to all the elements of an array Arrays.fill(intArray, 999); System.out.println(Arrays.toString(intArray)); |
Output
1 |
[999, 999, 999, 999, 999] |
You can also fill the partial array with given elements by specifying the start and end index. To fill the partial array, use the overloaded fill
method which accepts start index (inclusive) and end index (exclusive) as given below.
1 2 3 4 5 6 |
int[] intArray = new int[5]; //assigns 999 to elements having index of < 2 of an array Arrays.fill(intArray, 0, 2, 999); System.out.println(Arrays.toString(intArray)); |
Output
1 |
[999, 999, 0, 0, 0] |
How to compare two arrays using the equals method?
The equals
method returns true if the specified two arrays are equal to one another. It returns false otherwise. The two arrays are considered equal if they both contain the same elements at the same index locations.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
int[] intArray1 = {1, 2, 3}; int[] intArray2 = {1, 2, 3}; /* * To check if two arrays are equal, use * the equals method. */ System.out.println( "Two arrays equal? " + Arrays.equals(intArray1, intArray2) ); int[] intArray3 = {1, 2, 3}; int[] intArray4 = {1, 3, 2}; //not equal as the element order is different System.out.println( "Two arrays equal? " + Arrays.equals(intArray3, intArray4) ); |
Output
1 2 |
Two arrays equal? true Two arrays equal? false |
Note: Two arrays are also considered equal if both of them are null.
The equals
method is overloaded for byte, short, char, int, long, float, double, and Object types.
How to compare two multidimensional arrays using the deepEquals method?
The deepEquals
method returns true if the specified two arrays are equal to one another. The equals
method does not work for the multidimensional arrays, that is where the deepEquals
method is useful. Consider below given example of comparing two multidimensional arrays using equals
and deepEquals
methods.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Integer[][] multiArray1 = {{1,2}, {2,3,4}}; Integer[][] multiArray2 = {{1,2}, {2,3,4}}; /* * The equals method does not work for the * multidimensional arrays. * * This will returns false even though both the * arrays are same. */ System.out.println("Arrays equal? " + Arrays.equals(multiArray1, multiArray2) ); /* * To compare two multidimensional arrays, use the * deepEquals method */ System.out.println("Arrays equal? " + Arrays.deepEquals(multiArray1, multiArray2) ); |
Output
1 2 |
Arrays equal? false Arrays equal? true |
What is the difference between equals
and deepEquals
methods? The equals
method does not work with the multidimensional arrays, while the deepEquals
method works for arrays with any number of dimensions.
How to copy an array to another array using the copyOf method?
The static copyOf
method returns a new array having elements copied from the specified array.
1 |
public static int[] copyOf(int[] originalArray, int length) |
If the specified length of the copied array is greater than the original array’s length, the remaining elements of the copied array are filled with the default value of the array type (which is 0 for int, null for an object). If the specified length of the copied array is less than the original array, the remaining elements of the original array are truncated and not included in the copied array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
int[] originalArray = {1, 2, 3, 4, 5}; /* * To copy elements of one array to another, use the * copyOf method. */ /* * This will copy elements of the original array * to the copied array having size of 10. * The elements from index 5 to 9 will be set as 0 since * the original array has only 5 elements. */ int[] copiedArray1 = Arrays.copyOf(originalArray, 10); System.out.println("Copied array contains: " + Arrays.toString(copiedArray1)); /* * This will copy elements of the original array * to the copied array having size of 2. * The elements at index 2 to 4 will be truncated since * the copied array can only hold 2 elements. */ int[] copiedArray2 = Arrays.copyOf(originalArray, 2); System.out.println("Copied array contains: " + Arrays.toString(copiedArray2)); |
Output
1 2 |
Copied array contains: [1, 2, 3, 4, 5, 0, 0, 0, 0, 0] Copied array contains: [1, 2] |
The copyOf
method is overload for boolean, byte, short, char, int, long, float, double, and Object types. The copyOf
method throws NegativeArrayIndexException if the specified length is less than zero, and NullPointerException if the original array is null.
How to copy a range of elements of one array to another using the copyOfRange method?
The copyOfRange
method copies elements of the specified array from given start to end index into a new array. The copyOfRange
method is overloaded to accept boolean, byte, short, char, int, long, float, double, and Object types. For this example, we will look at the int array.
1 |
public static int[] copyOfRange(int[] originalArray, int start, int end) |
This method copies the original array elements from start to end index to a new array. Here, the start index is inclusive while the end index is exclusive.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
int[] originalArray = {1, 2, 3, 4, 5}; /* * This will copy elements at index 1 and 2 (i.e. elements 2 and 3) to * the new array. The rest of the array elements are truncated and not * copied to the new array. */ int[] copiedArray1 = Arrays.copyOfRange(originalArray, 1, 3); System.out.println("Copied array contains: " + Arrays.toString(copiedArray1)); /* * This will copy elements at index 4 to 8 to the new array. * Since the original array does not have enough elements, only * the element at index 4 (i.e. 5) will be copied in the new array, and * rest of the elements of new array will be filled with of int which is 0. */ int[] copiedArray2 = Arrays.copyOfRange(originalArray, 4, 8); System.out.println("Copied array contains: " + Arrays.toString(copiedArray2)); /* * Remember, the end index can be greater than the array length, but the * start index cannot. It will throw ArrayIndexOutOfBoundsException if * you try to do that. */ int[] copiedArray3 = Arrays.copyOfRange(originalArray, 6, 7); System.out.println("Copied array contains: " + Arrays.toString(copiedArray3)); |
Output
1 2 3 4 5 |
Copied array contains: [2, 3] Copied array contains: [5, 0, 0, 0] Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException at java.lang.System.arraycopy(Native Method) at java.util.Arrays.copyOfRange(Unknown Source) |
Important: The copyOfRange
method throws if the start index is less than 0 or greater than the array length. However, the end index can be greater than the array length. If this is the case, the copied arrays elements will be filled with the default value of the array type (which is 0 in case of int) as given in the above example. The copyOfRange
also throws IllegalArgumentException if the start index is greater than the end index.
How to get Stream for an array using the stream method?
The stream
method returns a sequential stream for the specified array as the source. The stream
method is overloaded for int, long, double, and object types. For this example, we will have a look at an int array.
1 |
static IntStream stream(int[] intArray) |
This method returns a sequential IntStream for the given array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
int[] intArray = {1, 2, 3, 4, 5}; /* * To get the stream for an array, use the * stream method */ IntStream stream = Arrays.stream(intArray); //print an array using stream System.out.println("Printing array elements using stream"); stream.forEach(e -> System.out.println(e)); //get sum of all array elements using the stream System.out.println( "Array elements sum using stream: " + Arrays.stream(intArray).sum() ); //get average of all array elements using the stream System.out.println( "Array elements average using stream: " + Arrays.stream(intArray).average().getAsDouble() ); |
Output
1 2 3 4 5 6 7 8 |
Printing array elements using stream 1 2 3 4 5 Array elements sum using stream: 15 Array elements average using stream: 3.0 |
Java Arrays Examples
- How to find array element using Arrays class
- How to add array to ArrayList object using Arrays
- How to initialize ArrayList or LinkedList with elements using Arrays
- How to print ArrayList using Arrays
- How to remove duplicates from String[] array using Arrays
- How to convert comma separated String to ArrayList using Arrays
- How to convert array to HashSet using Arrays
- How to printing array elements using Arrays
- Convert String to ArrayList using Arrays
- Convert String to String[] using Arrays
- Convert String[] to String using Arrays
- How to check if array contains value using Arrays
- Sorting String array containing numbers using Arrays
- How to reverse array using Arrays
- Convert String[] to ArrayList using Arrays
- How to sort String[] array using Arrays
- How to get random elements from Java HashSet using the Arrays class
- How to convert TreeSet to array in Java
- How to convert LinkedList to array in Java
- How to convert array to LinkedHashSet
- Convert array to Vector using the Arrays class
References:
Arrays class Javadoc
Please let me know if you liked the Java Arrays class tutorial with examples in the comments section below.