Java

Arrays in Java | Explained

Arrays are a data type to store multiple values of the same type(int, string) and are thus referred to as “a datatype to store collection of a data”. If you are heading to store multiple values(of the same data type), you must make use of arrays in Java.

Arrays are a data structure that stores elements of a similar data type represented by indexes. An index is a numeric number that defines the location of an element in an array. This post briefly describes the arrays in Java with the following learning outcomes:

  • understanding the working of arrays in Java
  • declaring single and multi-dimensional arrays in Java
  • using arrays in Java

How arrays work in Java

The arrays in Java have several purposes to serve, like optimizing the code and getting specific data stored at a specific location. For this, arrays in Java are categorized into two major categories that are discussed in this section.

Single Dimensional Arrays

As the name of this type directs, it is used to store elements one after another in a linear memory location. One of the following syntaxes will assist you in declaring a one-dimensional array:

datatype[] array-name;

The description of the syntax is provided below:

  • the datatype shows the datatype(of elements) that you want to store, and the datatype must be from the category of primitive data types(int, string, float, double, char, etc) of Java
  • the array-name refers to the identifier that is defined by the user(cannot use predefined keywords of Java)
  • additionally, the length of the array can be fixed by defining a number in parenthesis [ ].

Before initialization, instantiation is necessary to carry out by using the new operator of Java. The instantiation creates an instance of the same datatype and allocates memory as well. For instance, the following statement helps in the instantiation of :

datatype[] array-name=new datatype[a];

– the datatype must be the same on both sides and the [a] represents the index size of the array.

Note: If you declare and initialize arrays in a single line you may skip the instantiation in such a situation.

Multi-Dimensional Arrays

In contrary to single-dimensional arrays (which store variables), this category allows you to store multiple arrays in a single array. Furtherly, multi-dimensional array may be of 2-D(2-dimensions) or 3-D(3-dimensions). The following syntax refers to declaring multi-dimensional arrays:

datatype[][] array-name; //for 2-dimensional arrays

datatype[][][] array-name; //for 3-dimensional arrays

How to use arrays in Java

This section provides the usage of single and multi-dimensional arrays in Java. For better understating, this section is divided into several sub-sections that refer to various operations of arrays in Java.

How to declare one-dimensional(1-D) arrays in Java

The one-dimensional arrays in Java are declared by following the syntax provided in the above section.

The statement provided below declares a one-dimensional array in Java that stores only the string datatype of elements. The name of the string is set to laptops,

String[] laptops=new String[5];

The above statement is utilized in the following Java code:

package newpack;

public class Arrays {
    public static void main(String[]args) {
       
        //declaring and instantiating the array
        String[] laptops=new String[3];
       
        //initializing the 1st element of an array
        laptops[0]= "HP";
       
        //initializing the 2nd element
        laptops[1]="Dell";
       
        //initializing the 3rd element
        laptops[2]="Lenovo";
       
        System.out.println(laptops[0]);
        System.out.println(laptops[1]);
        System.out.println(laptops[2]);
    }
}

The above code is explained here:

  • declares an array and sets the limit to 3 indexes
  • initializes all elements by allocating the index number to each
  • printing the values stored at various index numbers
  • The output of the code is shown in the following image

Graphical user interface, text, application Description automatically generated

However, an array can be declared, instantiated, and initialized in one statement as well. For instance, the statement provided below helps to do so:

String[] laptops= {"HP", "Dell", "Lenovo"};

How to declare and initialize multi-dimensional arrays

The following Java statement allows you to create an array that stores integer values in 2-Dimensions.

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

The statement is explained here:

  • the int data type is used
  • the name of the array is set to num.
  • stores two arrays {1,2} and {3,4,5} in a single array

Moreover, the above statement is exercised in the following Java code:

package newpack;

public class Arrays {
    public static void main(String[]args) {
       
        //declaring a 2-D array
        int[][] num= {{1,2},{3,4,5}};
       
        //getting the length of first array in num
        System.out.println(num[0].length);
       
        //getting the length of second array in num
        System.out.println(num[1].length);
    }
}

The description of the code is provided below:

  • declares a 2-D array named num and stores 2 arrays in it
  • returns the length of 1st array in num-array
  • shows the length of 2nd array in num-array

The output of the code is shown below:

Graphical user interface, text, application Description automatically generated

How to use for loops in Java arrays

The loops play a crucial role in printing values of arrays in Java. It is observed that the System.out.println() statement only prints the variables one by one and you may have to write multiple statements to get all the data stored in an array. To overcome this issue, loops are an effective way to print all the data stored in an array at once. Here, we are exercising the for loop for 1-Dimensional and 2-Dimensional arrays in Java.

Using for Loop in one dimensional(1-D) arrays

The For loop in Java have three parts to consider that are followed by the syntax provided below:

for(initialization, condition, increment/decrement);

The following Java code makes use of for loop that prints all the values in an array named laptops:

package newpack;

public class Arrays {
    public static void main(String[]args) {
       
        //declaring an array
        String[] laptops= {"HP", "Dell", "Lenovo"};
        int i;
        //using for loop
        for(i=0; i<laptops.length; i++)
        {
            System.out.println(laptops[i]);
        }
       
    }
}

The for loop used above is for a 1-D array and the description of the code is provided below:

  • declares an array named laptops
  • declares a variable (i) to be used in For loop
  • applies for loop by using variable i, the condition is set to less than equals to the length of array and the number 1 will be incremented after each iteration.
  • applying System.out.println() statement inside for loop

The output shows that by using one statement we have printed all the elements stored in Java.

Graphical user interface, text, application Description automatically generated

Using for loop in a 2-D arrays

The following Java code uses the for loop in 2-D arrays to get the print of all the elements of Java. While using for loop in 2-D arrays, you have to use nested for-loop. The code provided below practices the for loop in 2-D arrays:

package newpack;

public class Arrays {
    public static void main(String[]args) {
       
        //declaring an array
        String[][] cars= {{"BMW", "Toyota"}, {"Honda","Mercedez"}};
        int i,j;
        //using for loop using i
        for(i=0; i<cars.length; i++)
        {
            //again applying for loop using j
            for(j=0; j<cars.length; j++)
        {
                System.out.println(cars[i][j]);
        }
           
        }
       
    }
}

The code is described as:

  • declaring a 2-D array
  • declaring i and j variables
  • applying for loop on i
  • again, using for loop on j
  • printing the elements of cars[i][j]

The output of the code is shown below:

Graphical user interface, application Description automatically generated

Conclusion

The arrays in Java are used to store numerous elements of the same datatype either linearly or in multi-dimensions. This descriptive post provides a comprehensive guide on arrays in Java. The working mechanism of the arrays in Java is discussed in detail. Based on that, we have performed several operations that better demonstrate the concept of arrays in Java. Moreover, you would also learn to declare and initialize single and multi-dimensional arrays in Java.

Happy coding!!

About the author

Adnan Shabbir