Arrays in Java

Created December 13, 2023

While coding in Java, you'll come across many instances where you might want to store your data in an array. Array is a linear data structure, either single or multidimensional. It stores the data items based on an index value. 1.png

What Exactly is an Array?

It is basically a collection of data items arranged in linear order using a "key" or "index" value. This index value could start either with 0 or 1. In java specifically, it starts with 0. One important thing we should know about arrays is that the elements that we put in them are stored in a contiguous block of memory and are arranged in the memory by their index values.

Some basic characteristics of an array are as follows -

How to create an Array in Java?

So, a basic array in java can be declared in many ways. Following are a few ways:

  1. Declare and initialize at the same time - Here, we will first declare the name and data type of the array and then initialize(insert the data items of the array) in the same line. Following code illustrates how this method can be used:
int[] arr = {1,2,3,4,5};
  1. Declare first, initialize later - There are two ways of declaring an array by this method. Either we can simply declare first and then initialize the array(without declaring the array size), or we can declare the array with its size and then later initialize it.
 int [] arr;
 arr = new int[]{1,2,3,4,5};
int[] arr = new int[5];
  1. Multidimensional arrays - In this method, instead of declaring an array of single items we can declare an array of arrays or array of arrays of arrays, and so on... Here's an example of a 2D array:
int[][] twoDArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

The above 2D array could be visualized like this - 1.png

  1. Dynamic arrays - An ArrayList data structure is referred to as "dynamic array" in java. These are called "dynamic" as they provide the feature of dynamic resizing and dynamic memory allocation(which is not available in a primitive/normal arrays in java). ArrayList data structures are found in collection framework in java.util.package and it contains its own functions to add, remove, insert, update data items in the array. Here's a small demonstration for the same:
import java.util.*;

public class Main
{
	public static void main(String[] args) {
	    ArrayList<Integer> arrayList = new ArrayList<Integer>();
	    arrayList.add(1);
	    arrayList.add(2);
	    arrayList.add(3);
	    System.out.println("Array List: "+arrayList);
	}
}

You can also remove certain element using their index numbers or other parameter -

import java.util.*;

public class Main
{
	public static void main(String[] args) {
	    ArrayList<Integer> arrayList = new ArrayList<Integer>();
	    arrayList.add(1);
	    arrayList.add(2);
	    arrayList.add(3);
	    System.out.println("Array List: "+arrayList);
	    arrayList.remove(0); //remove the 0th index item
	    System.out.println("Array List: "+arrayList);
	}
}

Know that here we can directly print the whole array simply by using the print statement unlike a normal array(discussed in the next section). We'll see array lists with greater detail in a future blog, but for now this is it for array lists!

Iterating over an array

At first you might think you can easily print an array simply by using the print statement in java. But it is not as straightforward as it looks! If you try to print an array using a simple print statement, it will print memory location hashcode as a result. For example:

public class Main
{
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5};
		System.out.println(i);
	}
}

The above code will simply print a random value like: 1.png To print the items present in the array, we have to iterate over each element present in the array using a for loop. I usually make use of a for-each loop in java for that(used only when you don't have to access the index value of the elements that you're accessing while iterating over the array). Here's an example:

public class Main
{
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5};
		for(int i: arr){
		    System.out.println(i);
		}
	}
}

A simple example: Reversing an array of Strings!

So let's say we have a simple array of Strings and we want to print this array reversed. A basic approach would be to access the list and getting its length, and iterating over the list from end to beginning or from the last element to first element while printing each one of them. So for example, if we have an array like {"algonoob", "in", "devdojo"}:

  1. We will fetch the array length(n), in this case it is 3(n=3).
  2. Create a for loop starting from n-1(here 3-1=2) and ending at 0, which is basically from the last element to the first element. Eg - i from 2 to 0.
  3. while the for loop runs, it will print the i'th string in the array. So the output will give: devdojo in algonoob, all items have been reversed! Following is the code for the same:
import java.util.*;

public class Main
{
	public static void main(String[] args) {
	    String[] inputArray = {"algonoob", "in", "devdojo"};
	    int n = inputArray.length;
	    for(int i=n-1; i>=0; i--){
	        System.out.print(inputArray[i]+" ");
	    }
	}
}

Here's a short gif to describe the whole process: java list reverse.gif

Conclusion

The topic of arrays is undoubtedly one of the most easiest topics in programming, but also the most essential. Knowing correct syntax is very important for different use cases and we tend to forget certain syntaxes sometimes(personal experience). I hope this blog would be useful for my fellow programmers who sometimes forget certain syntaxes of declaring and initializing arrays and sheds some light on how exactly the arrays work in java. For more such posts on data structures and algorithms you can check out my page.

Thanks for reading! ✨🎄