Java Arrays Class
In this page:
Printing Arrays with toString()
Printing an array directly with System.out.println(arr) shows something like [I@1b6d3586 — the array's type and memory hash, not its contents — because arrays don't override toString(). Arrays.toString(arr) from java.util.Arrays gives you the readable [1, 2, 3] form instead.
Example: Printing Arrays with toString()
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 2, 3};
System.out.println(arr); // e.g. [I@1b6d3586
System.out.println(Arrays.toString(arr)); // [1, 2, 3]
}
}
Login to try C/C++/Java/PHP code in the editor
Sorting Arrays
Arrays.sort() sorts a primitive array in place in ascending order using a tuned dual-pivot quicksort, and it also works on object arrays (like String[]) as long as the elements implement Comparable or you supply a Comparator.
Example: Sorting Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 1};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
}
}
Login to try C/C++/Java/PHP code in the editor
Searching with Binary Search
Arrays.binarySearch() finds an element's index in O(log n) time, but only works correctly if the array is already sorted — running it on an unsorted array gives an undefined, unreliable result rather than a clear error.
Example: Searching with Binary Search
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int index = Arrays.binarySearch(arr, 7);
System.out.println(index);
}
}
Login to try C/C++/Java/PHP code in the editor
Filling Arrays
Arrays.fill() overwrites every element (or a specified range) with the same value in one call, which is convenient for resetting a counting array or initializing a buffer to a sentinel value like -1 before real data is written in.
Example: Filling Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
Arrays.fill(arr, -1);
System.out.println(Arrays.toString(arr));
}
}
Login to try C/C++/Java/PHP code in the editor
Copying Arrays
Arrays.copyOf() creates a new array with the same or a different length, copying over as many original elements as will fit and padding the rest with default values if the new array is larger. This is one common way Java code implements a manual resize since arrays themselves can't grow.
Example: Copying Arrays
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int[] original = {1, 2, 3};
int[] copy = Arrays.copyOf(original, 5);
System.out.println(Arrays.toString(copy));
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: