Java Arrays Tutorial – Programming Code Examples
Java

Java Arrays Tutorial14 min read

How do you declare an array in Java?

Arrays are data types that store multiple values of a single type. An array is an object in Java itself and is created with new keyword.

The figure shows the schematic representation of an array in which 5 elements can be stored. This length of an array is always constant and can not be changed after the declaration.

java array declare




The stored values themselves must always be of the same type. Permitted here are any primitive data types or objects. Even other arrays can be stored in an array. See also the section on multidimensional arrays below.

If the above array is to be e.g. to store int values, their declaration follows in the following way:

It starts on the left with the name of the data type to be saved, followed by an opening and a closing square bracket. This together identifies the present array data type. After the then variable identifier, which has to comply with the usual conventions and the assignment operator, note the keyword new to create the array object. It is followed again by the data type with square brackets. Here, however, the length of the array, ie the number of memory locations, must be noted as a positive, integer value. A semicolon completes the expression.
As already mentioned above, the size of an array is basically not changeable. If the number of values ​​to be stored increases during the runtime of a program, this must be taken into account in the declaration either by declaring a sufficiently large array or by using another data type for storage, such as an ArrayList, from the beginning.

Conversely, memory spaces of an array can remain empty. During access, depending on the stored data type, either the default value or zero is used.
Incidentally, the parentheses can also be written after the variable identifier instead of after the type identifier.

However, this spelling is not recommended and you should prefer the notation of parentheses after the data type identifier, because only in this way a unique data type specification is present.

If an array without object formation is to be declared, the following notation is also possible:

The initialization of an array in Java

A newly created array is soon empty. His storage spaces still have to be occupied.
The individual entries of an array are numbered consecutively. One speaks of the index of the respective position. From the above scheme it can be seen that the counting of the indices starts at 0, so that an array of length 5 has the indices of 0-4.

The initialization of an array takes place by assigning the respective value to the special array position, which is called via the index.,

As mentioned above, an array position may also remain empty. If this is the case, the default value of the respective data type is used when accessing the memory location.

If a newly formed array is to be assigned values immediately at the declaration, then an array can also be declared and initialized at the same time. This happens in the following way:

Attention! However, a new assignment of an existing array object is not possible in this way.

Access to the stored values of an array in Java

The values stored in an array can be accessed through the index. Referring to the example above, the value stored in the fourth digit (Index 3!) Is accessed by the following expression:

The following example summarizes what has been said so far. An array of length 5 is generated and occupied in a loop at each position with the value of the count index. The termination condition accesses the length of the array. It can be determined by its length property. The value stored at each position is then output to the console.

output:

java array example

java array example

 

Multi-Dimensional arrays in Java

Arrays can themselves contain other arrays. One then speaks of multidimensional arrays. The opposite shows the scheme of a two-dimensional array containing 3 5-length arrays, which can be declared in the following way.

Multi-Dimensional arrays in Java

Theoretically, any memory depth is conceivable. But already three-dimensional arrays are not often found, since readability decreases rapidly with increasing memory depth.

In the above example, the stored arrays are the same size. However, multidimensional arrays can also store arrays of different sizes. Here is an example of a combined declaration and initialization of such an array:

However, this is not recommended, as the risk of accessing invalid indexes is high and in this case an IndexOutOfBoundsException is thrown.

As with one-dimensional arrays, the values for multi-dimensional arrays are also accessed via the indices.
In the following example, the previously mentioned is summarized again slightly varied.
A two-dimensional array is declared and initialized with three string arrays, each containing four address data. The array at the third position (index 2) is then replaced by another one. In two nested loops, all content is finally read out. Note how within the inner loop, the index is used to access the arrays stored at each location.

Output:

java multi-dimensional arrays

java multi-dimensional arrays

 

Processing Arrays in Java

When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.

Example

Here is a complete example showing how to create, initialize, and process arrays:

Output:

java example 1

 

The foreach Loops in Java Arrays

JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.

Example

The following code displays all the elements in the array myList :

Output:

java example 2

Passing Arrays to Methods in Java

Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array −

Example

Output:

java example 3

Returning an Array from a Method in Java

A method may also return an array. For example, the following method returns an array that is the reversal of another array:

Example

Output:

java example 4

The Arrays Class in Java

The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

Method – Description
public static int binarySearch(Object[] a, Object key)

Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, it returns ( – (insertion point + 1)).

public static boolean equals(long[] a, long[] a2)

Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.)

public static void fill(int[] a, int val)

Assigns the specified int value to each element of the specified array of ints. The same method could be used by all other primitive data types (Byte, short, Int, etc.)

public static void sort(Object[] a)

Sorts the specified array of objects into an ascending order, according to the natural ordering of its elements. The same method could be used by all other primitive data types ( Byte, short, Int, etc.)

 

Java Array Examples

 

Example 1: Program to Calculate Average Using Arrays

 

Example 2: Find largest element in an array

 

Example 3: Program to Add Two Matrices

Example 4: Program to Multiply Two Matrices

Example 5: Print an Array using For loop

Example 6: Print an Array using standard library Arrays

Example 7: Print a Multi-dimenstional Array

Example 8: Concatenate Two Arrays using arraycopy

Example 9: Concatenate Two Arrays without using arraycopy

Example 10: Check if Int Array contains a given value

Example 11: Check if array contains given value using Stream

Example 12: Check if array contains a given value for non-primitive types

Example 13: Convert list to array

Example 14: Convert Array to list

Example 15: Convert Array to Set

Example 16: Convert Array to Set using stream

Example 17: Convert Set to Array

Example 18: Convert Byte Array to Hex value

Example 19: Convert Byte Array to Hex value using byte operations

Example 20: Convert File to byte[]

Example 21: Convert byte[] to File

Example 22: Sort ArrayList of Custom Objects By Property

 

Leave a Comment