Arrays are an important part of the Java language, and they’re used to store and access data quickly and efficiently. Knowing how to properly use arrays is essential for developing flawless applications in Java. In this article, you will learn Java arrays example programs and how to create, fill, access, update, remove, and sort values in arrays, as well as find and iterate through data. By the end of this article, you should understand how to use arrays in Java.
What is an Array in Java?
A Java array is a type of object used to store multiple values in a single variable. Arrays give developers a way to easily allocate memory for multiple variables at once. It’s important to note that each value in an array must be of the same data type. In addition, all arrays in Java come with a predetermined number of elements, which means that the size of an array must be declared when it is initialized.
Arrays are also used to store collections of objects. This is especially useful when dealing with large amounts of data, as it allows developers to easily access and manipulate the data. Additionally, arrays can be used to store multiple values of different data types, as long as the data types are compatible. For example, an array can store both integers and strings, as long as the array is declared as an array of objects.
Creating an Array in Java
You can create an array in Java by using the array type syntax followed by the type of elements the array will contain. For example, the code below creates a string array called “arr” with 10 elements:
String[] arr = new String[10];
An array can also be initialized with values by simply filling in the elements separated by commas. For example, the code below initializes “arr” with five string values:
String[] arr = {"Hello", "My", "Name", "is", "John"};
Once an array is created, you can access and modify its elements using the array index. For example, the code below sets the first element of “arr” to “Hello World”:
arr[0] = "Hello World";
Adding Values to an Array in Java
Adding values to an array is done by accessing the index of each element and assigning a new value to it. For example, the code below adds a new value to the third element of the “arr” array:
arr[2] = "Smith";
It is also possible to add multiple values to an array at once. This can be done by using the arraycopy() method, which takes the source array, the starting index of the source array, the destination array, the starting index of the destination array, and the number of elements to be copied. For example, the code below adds the values from the “arr2” array to the “arr” array:
System.arraycopy(arr2, 0, arr, 3, arr2.length);
Accessing Values from an Array in Java
You can access values from an array by using the index value for each element. For example, the code below prints the first element of the “arr” array:
System.out.println(arr[0]);
You can also access multiple elements from an array by using a loop. For example, the code below prints all the elements of the “arr” array:
for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]);}
Updating Values in an Array in Java
Updating values in an array is similar to adding values. To update values, simply access the element index and set a new value. For example, the code below sets the fourth element of the “arr” array to “Mary.”
arr[3] = "Mary";
It is important to note that when updating values in an array, the new value must be of the same data type as the array. For example, if the array is an array of integers, the new value must also be an integer. If the new value is of a different data type, an error will be thrown.
Removing Values from an Array in Java
Removing values from an array is done by setting the element at a certain index to null. For example, the code below sets the last element of the “arr” array to null:
arr[4] = null;
It is important to note that this does not actually remove the element from the array. Instead, it just sets the value of the element to null. To actually remove the element from the array, you must use the ArrayList class, which provides methods for adding and removing elements from an array.
Sorting Arrays in Java
Sorting an array in Java is done by using the sort() method. This method takes in two parameters: a Comparator and a start index (which is optional). The Comparator parameter specifies how two elements should be compared and sorted, while the start index defines the starting point for sorting. For example, the code below sorts the “arr” array using a Comparator that compares two strings alphabetically:
Arrays.sort(arr, Comparator.comparing(String::toString));
The sort() method can also be used to sort an array of objects. To do this, the Comparator parameter must be set to a custom Comparator that compares two objects. This custom Comparator must implement the compare() method, which takes in two objects and returns an integer value. If the returned value is negative, the first object is considered to be less than the second object; if the returned value is positive, the first object is considered to be greater than the second object; and if the returned value is zero, the two objects are considered to be equal.
Searching for a Value in a Java Array
Searching for a value in a Java array is done by using the binarySearch() method. This method takes three arguments: the array to search in, a key to match against the elements, and an optional start index. The key argument is used to find matching values in the array and return their index. For example, the code below searches for “Mary” in the “arr” array and prints its index if it exists:
int index = Arrays.binarySearch(arr, "Mary");if (index >= 0) { System.out.println("Found at index: " + index); } else { System.out.println("Not found"); }
Iterating Through a Java Array
You can iterate through a Java array using either a for or for-each loop. The for-each loop is particularly helpful as it allows developers to access each element of the array without having to specify an index. For example, the code below uses a for-each loop to print each element of “arr” to the console:
for (String element : arr) { System.out.println(element); }
Processing Arrays with Streams
You can process arrays with Streams and use various methods such as map(), filter(), reduce(), and collect() to perform operations on them. Streams provide developers with an efficient way to process large amounts of data quickly and efficiently. For example, the code below uses Streams to print all values in “arr” that are longer than five characters:
arr.stream() .filter(element -> element.length() > 5) .forEach(System.out::println);
Conclusion
In this article, we discussed how to use arrays in Java, including how to create and fill them, access values from them, update values in them, remove values from them, sort them, search them, iterate through them, and process them with Streams. Knowing how to work with arrays is essential for all Java developers as they are used extensively throughout the language.