Back to home
Logicmojo - Updated March 18, 2023



Java remains one of the world’s most popular and used programming languages due to its platform independence. Many new developers learn Java as their first language. Java is known for being verbose, and some developers struggle to get the basics down.



Understanding data structures is a key component to Java programming, and arrays are the first step. To help your Java journey, in this tutorial, we will learn how to implement and use arrays in Java. A Java array is a group of similarly-typed variables that use a shared name.


What are arrays in Java?


An array refers to a data structure that contains homogeneous elements. This means that all the elements in the array are of the same data type. Let's take an example:


An array in Java is a group of like-typed variables referred to by a common name. Arrays in Java work differently than they do in C/C++. Following are some important points about Java arrays.

 β€’ In Java, all arrays are dynamically allocated.

 β€’ Since arrays are objects in Java, we can find their length using the object property length. This is different from C/C++, where we find length using sizeof.

 β€’ Java array can be also be used as a static field, a local variable, or a method parameter.

 β€’ The variables in the array are ordered, and each has an index beginning from 0.


Types of Array in java

There are two types of array.
 β€’ Single Dimensional Array
 β€’ Multidimensional Array


Single Dimensional Array in Java


Before using the array, we must declare it. Like normal variables, we must provide data type of array and name of an array. Data type means which type of elements we want to store in Array. So, we must specify the data type of array according to our needs. We also need to specify the name of an array so that we can use it later by name.



  datatype[] arrayName;
 Or
 datatype arrayName[];
 Or
 datatype []arrayName;





Multidimensional Array in Java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java



  dataType[][] arrayRefVar;
 Or
 dataType [][]arrayRefVar;
 Or
 dataType arrayRefVar[][];
 Or
 dataType []arrayRefVar[];





Memory representation of single dimensional arrays in Java


As soon as the compiler executes the code int a[] = new int[5]; First, it creates a reference variable named β€˜arr’. This variable points to the data that is stored in the array. The data items are contiguous and they are indexed from 0 to (length of the array -1). In this case, it is from 0 to 4.


Setting up an Array


Now that arrays are well-defined, let's dive into their usages. We'll cover a lot of topics teaching us how to use arrays. We'll learn some basics like how to declare and initialize an array, but we'll also cover more advanced subjects like sorting and searching arrays. Let's go first with declaration and initialization.


Declaration

We'll begin with the declaration. There are two ways to declare an array in Java:

 β€’ int[] anArray;


Initialization

Now that it's time to see how to initialize arrays. Again there are multiple ways to initialize an array. We'll see the main ones here, but this article covers arrays initialization in detail.

Let's begin with a simple way:

 β€’ int[] anArray = new int[100];

By using this method, we initialized an array of hundred int elements. Note that we need to specify the size of the array. When using this method, we initialize each element to its default value, here 0. When initializing an array of Object, elements are null by default.

We'll now see another way giving us the possibility to set values to the array directly when creating it:

 β€’ int[] anArray = new int[] {1, 2, 3, 4, 5};

Here, we initialized a five element array containing numbers 1 to 5. When using this method we don't need to specify the length of the array, it's the number of elements then declared between the braces.


Accessing Elements

Each element in the array is accessed via its index. The index begins with 0 and ends at (total array size)-1. All the elements of array can be accessed using Java for Loop.


// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
  System.out.println("Element at index " + i +" : "+arr[i]);


Implementation


// Java program to illustrate creating an array
// of integers, puts some values in the array,
// and prints each value to standard output.

class ArrayImplement
{
	public static void main (String[] args)
	{		
	// declares an Array of integers.
	int[] arr;
		
	// allocating memory for 5 integers.
	arr = new int[3];
		
	// initialize the first elements of the array
	arr[0] = 1;
		
	// initialize the second elements of the array
	arr[1] = 2;
		
	//so on...
	arr[2] = 3;
		
	// accessing the elements of the specified array
	for (int i = 0; i < arr.length; i++)
		System.out.println("Element at index " + i+ arr[i]);		
	}
}


What happens if we try to access elements outside the array size?

JVM throws ArrayIndexOutOfBoundsException to indicate that the array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of an array.


Common Java array operations


Add a new item to an Array

Since arrays hold a fixed size of values, we cannot add items that exceed the limit. Instead, we can declare a larger array and copy the elements of the smaller array into it. The Arrays class has a method to replicate the values of an array for this purpose.


  int[] newArray = Arrays.copyOf(array, array.length + 1);
 newArray[newArray.length - 1] = newItem;





Transforming an Array into a List


Arrays are great, but sometimes it can be handier to deal with List instead. We'll see here how to transform an array into a List. We'll first do it the naΓ―ve way, by creating an empty list and iterating over the array to add its elements to the list:


int[] anArray = new int[] {1, 2, 3, 4, 5};

List<Integer> aList = new ArrayList<>();
for (int element : anArray) {
    aList.add(element);
}

But there is another way, a little bit more succinct:

Integer[] anArray = new Integer[] {1, 2, 3, 4, 5};
List<Integer> aList = Arrays.asList(anArray);


The static method Arrays.asList takes a varargs argument and creates a list with the passed values. Unfortunately, this method comes with some drawbacks:
 β€’ It's not possible to use an array of primitive types

 β€’ We can't add or remove elements from the created list, as it'll throw an UnsupportedOperationException


From an Array to a Stream

We can now transform arrays into lists, but since Java 8 we have access to the Stream API and we might want to turn our arrays into Stream. Java provides us with the Arrays.stream method for that:



  String[] anArray = new String[] {"Milk", "Tomato", "Chips"};
 Stream aStream = Arrays.stream(anArray);





When passing an Object array to the method it will return a Stream of the matching type (e.g. Stream for an array of Integer). When passing a primitive one it will return the corresponding primitive Stream.

It's also possible to create the stream only on a subset of the array:

Stream anotherStream = Arrays.stream(anArray, 1, 3);

This will create a Stream with only β€œTomato” and β€œChips” Strings (the first index being inclusive while the second one is exclusive).


Passing arrays to a method

Arrays can be passed to a method. This enables the method to access and perform operations on the array. Various algorithms can be applied to the array once a particular method can access it.
Syntax for passing arrays to method: method_name(name_of_array)


Array class in Java


The array class in Java is particularly useful for performing functions that are tedious to write manually. It has a lot of methods for creating and accessing Java arrays. It also includes sorting, searching, and a lot of popular functions that are frequently useful by programmers to manipulate arrays. This is a part of the java.util package. This class inherits from the Object class. Some of the useful methods are as below :


Java toString


This method converts the array to a string which can then be easily printed without using for loops. This converts the array to string form, by separating each of its elements with a comma and enclosing the array within square brackets. It enables the programmer to print the array without having to use loops.

Syntax

Arrays.toString();


Java Compare

This method simply compares the two arrays passed in its arguments lexicographically. This returns 0 if the arrays are the same. The syntax is:
Arrays.compare(array1,array2)


Java equals

Java equals method returns true if both the arrays that are to be compared are equal. If not it returns false. However, the deepEquals method is useful to check whether multidimensional arrays are equal to one another(i.e it returns true if the corresponding pairs of elements are equal even in nested arrays of arbitrary depth. Syntax:
Arrays.equals(Object Array1,Object Array2)
Arrays.deepEqual(Object Array1,Object Array2)


Sorting Arrays

Let's now see how to sort an array, that is rearranging its elements in a certain order. The Arrays class provides us with the sort method. A bit like the stream method, sort has a lot of overloadings.
There are overloadings to sort:
 β€’ Primitive type arrays: which are sorted in ascending order
 β€’ Object arrays (those Object must implement the Comparable interface): which are sorted according to the natural order (relying on the compareTo method from Comparable)
 β€’ Generic arrays: which are sorted according to a given Comparator
In addition, it's possible to sort only a specific portion of an array (passing start and end indices to the method).
The algorithms behind the sort method are quick sort and merge sort for primitive and other arrays, respectively.

Let's see how this all work through some examples:


int[] anArray = new int[] {5, 2, 1, 4, 8};
Arrays.sort(anArray); // anArray is now {1, 2, 4, 5, 8}

Integer[] anotherArray = new Integer[] {5, 2, 1, 4, 8};
Arrays.sort(anotherArray); // anotherArray is now {1, 2, 4, 5, 8}

String[] yetAnotherArray = new String[] {"A", "E", "Z", "B", "C"};
Arrays.sort(yetAnotherArray, 1, 3, 
  Comparator.comparing(String::toString).reversed()); // yetAnotherArray is now {"A", "Z", "E", "B", "C"}


Searching in an Array

Searching an array is pretty simple, we can loop over the array and search our element among the array elements:


int[] anArray = new int[] {5, 2, 1, 4, 8};
for (int i = 0; i < anArray.length; i++) {
    if (anArray[i] == 4) {
        System.out.println("Found at index " + i);
        break;
    }
}


Here we searched for number 4 and found it at index 3. If we have a sorted array though, we can use another solution: the binary search.

Fortunately, Java provides us with the Arrays.binarySearch method. We have to give it an array and an element to search. In case of a generic array, we also have to give it the Comparator that was used to sort the array in the first place. There is again the possibility to call the method on a subset of the array. Let's see an example of the binary search method usage


int[] anArray = new int[] {1, 2, 3, 4, 5};
int index = Arrays.binarySearch(anArray, 4);
System.out.println("Found at index " + index);


Conclusion

In this detailed article we've covered basic and some advanced usages of arrays in Java.

Good Luck & Happy Learning!!