What are Arrays in Java?

Share your love

An array is a type of data structure that can store a fixed number of elements of the same data types in our RAM in contiguous order, and Arrays in Java are no exception. It has the same features as any other array except that in Java, an array is considered to be an object that stores elements of the same data type and a fixed size.

Arrays are usually declared so that we can store multiple values in one go and we don’t have to declare and initialize each value separately.

Let’s take an example to understand the above-said line. Let’s say in a class there are 100 students and we want to store their names in our system for the class record. 

One way is to use a data type string and declare and initialize 100 different variables to store them. A better approach will be to make an array of size 100 and the same data type- in this case, string and store all the names in it.

This is because the former process will consume a lot of time and is repetitive, while the latter method is much better as no time is wasted and with one declaration all the values have been initiated and declared, and even stored.

String[] Class = new String[100];// declaring and allocating a memory of 100 strings
Class = {"Ateev", "Arun", "Rohit" ..... "Subash"};// initializing elements

In the above example, we have created an array of fixed size (100) which is equal to the amount of data we have to store in it.

Indexing of Arrays in Java

In most programming languages (Java included), the indexing of arrays starts from 0 and goes to 1 less than the size or length of the array.

Arrays in java
Arrays Indexes

Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the image, indexing begins at 0 and ends at 8 which is 1 less than its length.

Declaring Arrays in Java

In Java, there are 2 ways in which we can declare an array.

int[] A;
    OR
int A[];

When it comes to declaring an array or a variable in java, the syntax is the same. They both need a data type so that the JVM can tell which type of values will be stored and a name that can be anything we want, provided that it follows the rules of naming a variable in Java. 

In the above syntax int is the data type or primitive data type to be more specific and A is the name of the array the empty braces symbolize that the variable holds an array whose size is yet to be determined.

We cannot provide the size of the array in the declaration part as the Java compiler will throw an error saying unexpected token/identifier, etc.

error
error

As with variables, the declaration does not create an array; it has just created a reference of that array which tells the compiler that this variable will hold an array of the specified type. To link this Array with the actual physical array of the same type, we must allocate one using the new keyword and assign it to typeArray.

To keep the syntax of Array easy to read and understand and similar to the syntax of declaring a variable, the first syntax — int[] A; is commonly used, and the empty brackets brackets identifies the array type and should appear with the type designation.

Similar to int there is another data type as well which can be used to declare an array.

byte[] A;           // an array of Bytes
short[] A;          // an array of Shorts
int[] A;            // an array on Integers
long[] A;           // an array of Long
float[] A;          // an array of Floats
double[] A;         // an array of Doubles
boolean[] A;        // an array of Boolean
char[] A;            // an array of Characters
String[] A;         // an array of Strings

Initializing Arrays in Java with Memory Allocations

To initialize an array in java, we can use the index value which as told starts from 0 and ends at 1 less than the length of the array.

In the case of names of students, we can initialize the array as

String[] Class = new String[100];//
Class[0] = "Ateev";
Class[1] = "Arun";
Class[2] = "Bimal";
.
.
.
.
.
Class[99] = "Zahid";

This process is too lengthy and time-consuming, and thus we have a short-hand trick that we can use to reduce the time.

int[] A = {"Ateev", "Arun", "Bimal", ........, "Zahid"};

In this case, java automatically determines the length of the array by counting the values between the braces and separated by commas.

Another way to create an array is by using the new keyword as we did in the above example where we have made an array to store the name of 100 students. This method is generally used when we want to take the input from the user.

type[] name;// declaring an array
name = new type[size]// allocating memory to it

It can also be written as –

dataType [] name = new dataType [size]; //declaring and initializing array at the same time
// example 
String[] Class = new String[100];

It is not possible to declare the array with one data type and initialize it with another data type. In both cases, the data type should be the same

Printing the Elements of an Array

If we want to print the values of an array, one way is to again use the index values and print the array. 

Printing an Array in Java using its index values
Printing an Array in Java using its index values

This method fails when we have an array of say 100 sizes like the one discussed above and we want to print its values. But there is one more method through which we can find out the values of the array without using the indexes and that is loops.

There are two types of loops through which we can find the value of the array –

  1. For Loop
  2. ForEach Loop

The For Loop

The for loop is the same one we have used plenty of times while calculating or writing programs in java or any other programming language. It has the same syntax as java also

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}
Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.
The for loop
The for loop

Notice that our loop is running only till a.length-1 and that is because array indexing starts from 0 and ends at 1 less than the size of the array.

The For Each Loop – Enhanced For Loop

The for-each loop works like a loop but rather than iterating over indexes like for loop, it iterates over the elements or the values of the array. Its syntax is as follows-

for (type variableName : arrayName) {
  // code block to be executed
}

Let’s see and understand all the above concepts practically using real-world examples – 

Q1. Find out the sum and average of the given array in java.

A = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12}

class Main {
 public static void main(String[] args) {
        int[] A = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};
        int sum = 0;
        for (int i=0; i<A.length; i++) {
            sum = sum+A[i];
        }
        System.out.println("SUM " + sum);
        int n = A.length;
        double average = (double) sum / (double) n;
        System.out.println("AVERAGE " + average);
    }
}

Answer
Answer

Types of Arrays

  1. Single Dimension Array – 1D
  2. Multidimensional Array – 2D, 3D, 4D….

Until now we have mainly covered all the basic concepts of 1D Array and understood them practically as well. But now it’s time to understand those concepts in the form of a Multidimensional Array as no matter the type of the array, its concepts remain unchanged.

Multidimensional Array

Multidimensional arrays can also be referred to as an array of arrays as each element of the multidimensional array is an array itself, and there is no limit to the number of elements each array of the multidimensional array can store, it’s again up to the type of data we have declared it with. To understand this, assume a 2D Array of n rows and m columnn x m matrix

As it is an array, its declaration and initialization are mostly the same as the 1D array except for the notation which will now be double square brackets rather than a one ([][])

int[][] arr = new int[n][m];

Where n is the size of the rows and m is the size of the column of a 2d matrix that will be formed and the maximum number of elements the array can store will be n*m or the maximum length of this array.

Let’s understand this with an example – say the size of the row is 3 while the size of the column is 4, thus the maximum number of elements it can hold is 12. See the image below to get a better grasp of the topic.

2D Array
2D Array

As told already, the length of every row or every column doesn’t need to be the same. Consider the following example – 

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

It can be represented as – 

These types of arrays where the number of columns in each row has different lengths or an unequal number of elements are present in each column is called a Jagged Array.

In the above example, we have created a multidimensional array named ‘a’. Since each component of a multidimensional array is also an array (a[0], a[1], and a[2] are also arrays.

Let’s understand how to Print the elements of a 2D array.

How to Print Elements of a 2D Array

We have already seen one way of printing the elements of a 2D array and that is using the index number of both row and column (see the above image). The other method is the same one we used to print the values of a 1D array – loops. Let’s see both of them at once.

class MultidimensionalArray {
    public static void main(String[] args) {
 
        int[][] a = {
            {1, -2, 3},
            {-4, -5, 6, 9},
            {7},
        };
      //for loop
        for (int i = 0; i < a.length; ++i) {
            for(int j = 0; j < a[i].length; ++j) {
                System.out.println(a[i][j] + " ");
            }
            System.out.println();
        }
    // for each loop
        for (int[] innerArray: a) { //accessing the individual array
            for(int data: innerArray) { // accessing each element inside the row
                System.out.println(data);
            }
        }
    }
}

In the case of ‘for loops’, we are using a nested loop system to iterate over both rows and columns and thus i represents the rows while j represents the columns.

The first loop is the basic for loop which will iterate till the last element (i<a.length) while in the second loop, we can see that the limit set for its iteration is a[i].length where i can be from 0 till a.length-1 depending on the upper loop as we have to iterate over j columns for i rows.

While in the case of for-each loops, the first loop will access the individual array as 2D arrays are nothing more than the collection of 1D arrays and the first loop will iterate through each of them. And the second loop will iterate over the columns or elements of that row, and finally, print them.

As we know that the output will be the same no matter which type of loop we choose to use to print its values.

OUTPUT

There is a built-in method for arrays that can be used in place of loops for both 2D as well as 1D arrays, and that is the Arrays.toString method which converts the array into a string by looping over each item of the array and then printing it within square brackets ([]) separated by commas.

class MultidimensionalArray {
    public static void main(String[] args) {
 
        int[][] a = {
            {1, -2, 3},
            {-4, -5, 6, 9},
            {7},
        };
      //Arrays.toString
        System.out.print(Arrays.toString(a[0]) + " ");
        System.out.println();
        System.out.print(Arrays.toString(a[1]) + " ");
        System.out.println();
        System.out.print(Arrays.toString(a[2]) + " ");
    }
}
OUTPUT

In multi Dimensional Arrays, there can be 3D Arrays, 4D Arrays, and so on, but the concepts will remain the same no matter which type of Array we are dealing with. The only difference will be in their declaration and initialization part as in a 3D array z-axis will be included with both the x-axis and y-axis and this goes on for 4D, 5D, etc.

The size of the array must be of either int or short data type, we can not use long data type to specify the size of an array. This is because an array can only store up to 2147483646 index values and long data type exceeds this limit.

Array Manipulations

Arrays are a powerful tool to have when we want to deal with multiple elements at the same time like searching for a certain element, copying arrays, sorting the elements in ascending order, and many more. Luckily, Java provides us with an Array Class which already has these methods and many more as a built-in feature. 

The ‘Arrays’ Class is a member of the ‘java.util’ package. This is a part of the Java Collections framework and provides methods to create, access, and manipulate Java arrays dynamically.

All the methods provided by the Arrays class are static and are methods of the ‘Object’ class. As the methods are static, they can be accessed using the class name itself.

Array Classes

As told above, Java.util.package contains several static methods through which we can easily access, create, and can even manipulate arrays dynamically. Let’s discuss some of them.

MethodDescription
asLint()Returns a list of fixed sizes from the specified array
binarySearch()It is used to search for a specific element using the binary search algorithm
compare(array1, array2)Compares the two arrays in lexicographical order
copyOf(origionalArray, newLength)Copies the original array up to the specified length
copyOfRange(originalArray, fromIndex, toIndex)Copies the original array upto the specified length given by index values
deepEquals(object[] 1, object[] 2)Returns true if the two specified arrays are deeply equal.
deepHashCode(Object[] a) Returns a hash code based on the “deep contents” of the specified Arrays.
deepToString(Object[] a)Returns a string representation of the “deep contents” of the specified Arrays.
equals(array1, array2)Returns true if the two specified boolean arrays are equal.
fill(originalArray, fillValue)Assign this fill value to each index of this array.
parallelPrefix(originalArray, operator)

parallelPrefix(originalArray, fromIndex, endIndex, functionalOperator)
Performs a mathematical function on either all the elements of the original array or up to a specific index value and updates the array.
sort(originalArray)sort(originalArray, fromIndex, endIndex)Sorts either the complete array or up to a specific index. 
toString(originalArray) It returns a string representation of the contents of this array. The string representation consists of a list of the array’s elements, enclosed in square brackets (“[]”). Adjacent elements are separated by the character a comma followed by a space.
Array Classes

You can read more about them in detail here.

Conclusion

An array in java is a collection of similar types of elements stored in contiguous memory locations. They are normally used to store multiple values of the same data type which if done individually will take a lot of time.

The stored elements can be called using their index value which starts from 0 and ends at 1 less than the length of the array which can be calculated using the .length property.

There are two types of arrays – 1D Array and Multidimensional Array which consist of 2D, 3D, and so on Arrays. In this blog, we have only discussed 1D and 2D Arrays but the concepts of Arrays remain the same for all types of arrays except their declaration and initialization part.

The way we declare an array is the same way we declare other data types but the only difference is that when we declare an array we use square brackets([]) and when we declare primitive or any other data types they are not used. They are used to tell us what type of array we are dealing with. If we have a single square bracket([]), then it’s a 1D Array, if there are two([][]), then 2D Array and it continues.

In this blog, we have also covered Array Classes which are a part of the util package of the object class which can be used to perform certain operations like sorting, comparing, copying array, etc, and the best part is these are all static methods which are dynamically called to perform these operations.

The main disadvantage of using an array is that we have to declare its size before inserting a value in it, and we somehow have inserted values that exceed the size of the array, the compiler will give us an error of out of bounds and we will not be able to perform any operation on that array unless we the length of the array is equal to the size specified. But that can easily be taken care of by using another class like Arrays of the util package – ArrayList.

ArrayList is a part of the util package and is used to create dynamic arrays which may be slower but are very helpful when we have to do lots of array manipulations. Even though we can create an array of any size, its toll can easily be seen in our RAM or the heap part of the memory when an array of a much bigger size is created in a contiguous order which will lead to waste of memory or memory leaks, We will discuss this in much detail in upcoming blogs.

Frequently Asked Questions

What are Arrays in Java?

Arrays can be understood as a container that holds a fixed number of elements of the same data type. And it is the same case in Java as well.

What is the difference between Array and ArrayList in Java?

An array is a data structure that holds a fixed number of elements of the same data type while in ArrayList these numbers are not fixed.

What are the same Advantages of Arrays?

  • An array can store multiple values in a single variable.
  • Arrays are fast as compared to primitive data types.
  • We can store objects in an array.
  • Members of the array are stored in consecutive memory locations.

How are Arrays created?

Arrays can be created using any data type but the values of the array must be of the same type. To create an array we have to create a data type with a square bracket followed by its initialization which is either up to the user to provide values or up to us to put some initial value for the operations.

int[] a = new int[n];

int[] A = {1, 2, 4, 5, 6}

What is an Array Class in Java?

The Arrays class is a member of the java util package which provides us a method to create, manipulate and access arrays dynamically with the methods provided to us which are static.

Share your love