Explained: Array Programs In Java

Explained: Array Programs In Java
Explained: Array Programs In Java

Introduction

Who doesn’t love eating chocolates, and I wonder what can be better than a box of assorted chocolates? But most of the time, we are more busy savouring the sweet delicacy rather than noticing the organised arrangements of the chocolates in the box.

Like the box of chocolates, an array is a programming tool that stores similar data together under a single name. Now, once we start eating the chocolates, doesn’t it become difficult to stop? We pick up one after the other. 

Similarly, once we know the address of the first element in an array, we can easily access the rest of them, one after another.


Thus we can define an array as follows:

An array is a collection of similar data stored in contiguous memory locations. So far, we only know what an array is, so let’s see some array programs in Java in the rest of this article. 

What type of data is stored in Arrays?

Now that we know what an array is, you may wonder about the kind of data stored in arrays. Like variables, arrays are used to store data. So they can store data in primitive data types like integer, decimal, boolean and character,

For example, the age of the students in a class can be stored in an array as follows:

int arr[] = {19, 19, 20, 19, 19, 19, 20};

The answers to a set of MCQ questions can be stored in a Boolean array as follows:

boolean arr[] = {true, false, true, true, true};

In Java, Strings and objects are classified as non-primitive data types. Therefore, since they are considered data types, they can be stored in an array too.

For example, a string array in Java containing the names of some people would be as follows:

String arr[] = {"Alfie", "Anwita", "Neelanjana", "Anwesha", "Krishna"};

Don’t worry about all the confusing syntax used above. We’ll discuss all of them in upcoming sections. Now that we know about the kind of data stored in arrays, let us see the different types of arrays in Java.

Types of Arrays in Java

An array stores data as we do in a matrix in maths. So, there are different types of arrays in Java based on the dimensions of the array. 

For example, there is a single-dimensional array in Java as shown below:

int arr[] = {19, 19, 20, 19, 19, 19, 20};

There is also a 2d array in Java which is similar to a 2×2 matrix in mathematics. A 2-D array is shown below:

int arr[][]={{1,2,3}, {4,5,6}, {7,8,9}};

Therefore, arrays programs in Java usually contain two kinds of arrays:

  • 1 D arrays
  • Multi-dimensional arrays

Now that we know the basic theory about arrays let us dive into the syntax.

Declaring Arrays in Java

We must declare any variable before using it. Similarly, in array programs in Java, we must declare arrays too. While declaring an array in array programs in Java, we can either initialise the array with elements or allocate the memory for the array. 

Let us see how to do that for a single-dimensional array first.

For single-dimensional arrays,

  • To declare and initialise the array with elements.
datatype[] array_name = {ELEMENTS};

OR

datatype array_name[] = {ELEMENTS};

For example,

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

OR

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

To allocate the memory for the array.

datatype[] array_name = new datatype[length_of_array];

OR

datatype array_name[] = new datatype[length_of_array];

For example,

int arr[] = new int[5];

Now that we know how to initialise a single-dimensional array, learning the same for a multi-dimensional array won’t be too much of a challenge.

GIF Source: GIPHY

For multi-dimensional arrays,

  • To declare and initialise the array with elements.
datatype[][] array_name = {{ELEMENTS IN ROW 1}, {ELEMENTS IN ROW 2},...};

OR

datatype array_name[][] = {{ELEMENTS IN ROW 1}, {ELEMENTS IN ROW 2},...};

Let us see an example to get a better picture of the syntax used.

int arr[][] = {{1,2,3},{4,5,6},{7,8,9}};
  • To allocate the memory for the array.
datatype[][] array_name = new datatype[number_of_rows][number_of_columns];

OR

datatype array_name[][] = new datatype[number_of_rows][number_of_columns];

An example showing the above would be,

int arr[][] = new int[2][3];

After allocating the memory for the array, the elements of the array must be taken as user input. We will see how to do that next.

How to initialise an Array in Java?

In Java, all the elements in an array are initialised to 0 for an integer array, false for a boolean array and null for a character array, by default. But we don’t want an array with default values in it. 

So, after declaring an array in Java, initialising it with the elements is our next step. 

We can initialise the array while declaring it as we already saw in the array declaration section, but most of the time, we need to initialise the array with an input given by the user, using the Scanner class. The code below shows how to do so for a multi-dimensional array, and once you know for a multi-dimensional array, tackling a 1-D array won’t be much trouble.

To know in-depth about using the Scanner class in Java, check out the blog here.

import java.util.*;
public class Main
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter m and n ");
        int m=sc.nextInt();
        int n=sc.nextInt();
        int arr[][]=new int[m][n];
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.println("Enter the element in position "+i+","+j);
                arr[i][j]=sc.nextInt();   
            }
        }
        for(int i=0;i<m;i++)
        {
            for(int j=0;j<n;j++)
            {
                System.out.print(arr[i][j]+" ");   
            }
            System.out.println();
        }
    }
}

Input:

Enter m and n 
3 3
Enter the element in position 0,0
4
Enter the element in position 0,1
2
Enter the element in position 0,2
3
Enter the element in position 1,0
1
Enter the element in position 1,1
5
Enter the element in position 1,2
2
Enter the element in position 2,0
6
Enter the element in position 2,1
7
Enter the element in position 2,2
8

Output:

4 2 3 
1 5 2 
6 7 8 

Now, we have an array declared and initialised, but what next? We may need to access the elements in the array, but do we know how to do that?

Not yet, but now we will find out next.

Accessing Array Elements

In Java, array elements are accessed with the help of what we call the index of the element. But what is this index? To understand this, let us again consider the example of our box of chocolates.

GIF Source: GIPHY

If we want to count the number of chocolates, we’ll start counting from one and the left.

So, in the picture above, there are four chocolates.

The indexing of the elements in array programs in Java is similar. We start counting from the left in arrays, but instead of counting from 1, we’ll start with 0. So, the indices’ of the elements in array programs is like this:

Now that we know the index of elements in array programs in Java, we can easily access the elements in an array with the following syntax:

array_name[index];

For example, if we want to print the number 3 from the array above, we will write:

arr[2];

While using the index of array elements, a common exception encountered is the ArrayIndexOutOfBoundsException. This exception is encountered when an element is accessed at a position greater than or equal to array length or at a position less than zero. 

You can learn more about it here.

Iterating Through an Array

We may need to iterate through the elements in array programs in Java to print them, access them or for some other reason. To do that, we need to use a loop, which is a for loop in most cases. Let us see an example of it. 

The code below iterates through a 1-D array and prints the elements. 

import java.util.*;
public class Main
{
	public static void main(String[] args)
	{
    	     Scanner sc=new Scanner(System.in);
    	     System.out.println("Enter the length of the array ");
    	     int n=sc.nextInt();
    	     int arr[]=new int[n];
    	     for(int i=0;i<n;i++)
           {
            	System.out.println("Enter the element in position "+i+" ");
            	arr[i]=sc.nextInt();   
        	}

    	     for(int i=0;i<n;i++)
    	     {
        	     System.out.print(arr[i]+" ");   
    	     }
	}
}

Input:

Enter the length of the array 
4
Enter the element in position 0 
3
Enter the element in position 1 
8
Enter the element in position 2 
5
Enter the element in position 3 
2

Output:

3 8 5 2 

Array Class in Java

A class is defined as a collection of methods and objects used to call the methods. So, the array class is a collection of array methods in Java used to perform certain operations on an array directly, without having to use loops.

These tasks include for example,

  • Initialising an array with elements
  • Sorting an array
  • Searching in an array

To use a class in Java, we must first import it from the necessary package. So, to use the array class in Java, we have to import it from java.util package as follows:

import java.util.Arrays;

Methods in the Array Class in Java

The following are a few examples of methods in the Array class:

Method NameSyntaxUse
binarySearchpublic static int binarySearch(int a[ ], int key)To search for an integer element in the array using binary search.
equalspublic static boolean equals(int a1[ ], int a2[ ])It checks whether two arrays have an equal number of elements and if all the corresponding elements are equal.
fillpublic static void fill(int[ ] a, int val)It assigns the value passed as a parameter to each element in the array.
toStringpublic static String toString(int[] a)It returns the elements of the array as a string.
sortpublic static void sort(int[ ] a)It sorts the given array in ascending order.

There are many more methods in the Array class in Java that you can read about in the official Java documentation.

Frequently Asked Questions

What is an array in Java?

An array is a contiguous memory block storing data of the same data type under a single name.

What are the different types of arrays in Java?

Arrays in Java are of two types:

1. One dimensional array
2. Multi-dimensional array

Give an example of an array in Java.

A one dimensional array in Java is as follows:
int arr[] = {19, 19, 20, 19, 19, 19, 20};
An example of a multi-dimensional array is:
int arr[][]={{1,2,3}, {4,5,6}, {7,8,9}};

Why does indexing start from 0 in computers?

Everything in a computer’s memory is stored in a specific address, with the help of which data is accessed. For a contiguous memory block, as in an array, the indexing starts from 0 so that we can access the successive elements by adding the index position to the address of the first element (here the 0th element) multiplied by the size of each element as follows:
nth element = address of 0th element + (n * size of the element)

How do we find the array length in Java?

To find the length of an array in Java, we use the length function as follows where the integer variable len stores the length of the array:
int len = array_name.length;

Key Takeaways

In this article, we got to know how to use arrays in Java. We saw a few methods used with arrays, and you may have even explored a few new one’s yourself. But is this the end of our discussion?

Definitely not, because theoretical knowledge plays a small role in the practical world. It is rigorous practising which helps us to hone our skills. You can find a wide variety of practice problems, specifically on arrays, to practically utilise the knowledge you gained here.

Apart from this, you can use CodeStudio to practise a wide range of DSA questions typically asked in interviews at big MNCs. This will assist you in mastering efficient coding techniques and provide you with interview experiences from scholars in large product-based organisations.

Happy coding!

By Neelakshi Lahiri

Exit mobile version