Arrays in Java

By | August 23, 2020

Arrays in Java:

Arrays class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists.The methods in this class all throw a NullPointerException, if the specified array reference is null, except where noted.

The documentation for the methods contained in this class includes briefs description of the implementations. Such descriptions should be regarded as implementation notes, rather than parts of the specification. Implementors should feel free to substitute other algorithms, so long as the specification itself is adhered to. (For example, the algorithm used by sort(Object[]) does not have to be a MergeSort, but it does have to be stable.)

This class is a member of the Java Collections Framework.

Since:
1.2

Arrays declaration:

Define the variable type with square brackets.

Example:

How to access an array:

We can access an array by referring to its index position.

Example:

Array index starts with 0. [0] is the first element and [1] is the second element and so on.

Change an Array element:

To change the specific array element we can use its index position.

Array length:

We can use the length property of an array to find how many elements are there in an array.

Loop through an Array:

We can iterate over an array using for loop. length property is used to know how many times we have iterate over an array.

Loop through an array with for-each:

for-each loop is exclusively used to loop through elements in arrays.

Below are the main methods present in Arrays class:

Arrays.binarySearch(a, key);
Arrays.copyOf(original, newLength);
Arrays.deepEquals(a1, a2);
Arrays.deepToString(a);
Arrays.equals(a, a2);
Arrays.sort(a);
Arrays.toString(a);

Recommended Posts:

Java map examples

Find the third largest number in an array in Java

Star pattern programs in Java

Leave a Reply

Your email address will not be published. Required fields are marked *