Java Arrays

Visual guide outlining fundamental aspects of Java arrays. Includes declaration, initialization, accessing elements, and insights into multidimensional arrays. A must-have reference for array manipulation in Java.

The arrays in Java

An array is a type of variable in Java that may hold one or more values of a similar type.

For example, an array of ten elements of a type integer can store 10 numbers.

int[] Intarr = {5,10,15,20,25,30,35};
for (int ArrItem : Intarr) {
    System.out.println("Array Element Value: " + ArrItem);
}
  • Array indices start from 0
  • Java Store elements of a specific data type
  • For mixed types consider using ArrayList or other collection classes

I will explain the elements and important points about Java arrays, first let me show you a few examples along with code for creating, initializing, and accessing arrays.

An example of int array

In this example, an array of five elements is created. The array is declared with type integer so it may store numeric values.

A for loop is used to iterate through the array elements. Inside the for loop, the elements are displayed by using System.out.println.

The array Java example code:

public class java_array {
    public static void main(String []args) {
        int[] Intarr = {5,10,15,20,25,30,35};

        for (int ArrItem : Intarr) {
            System.out.println("Array Element Value: " + ArrItem);
        }  
    }
}

Output:

Array Element Value: 5
Array Element Value: 10
Array Element Value: 15
Array Element Value: 20
Array Element Value: 25
Array Element Value: 30
Array Element Value: 35

An example of creating, initializing and displaying string array

In this example, a Java string array is created with five elements. The string array contains the names of cities.

The array is declared differently than the above example. After declaration, the values are assigned to each element as shown in the Java program below:

The string array code:

public class java_array {

    public static void main(String []args) {

        String[] World_cities = new String[5];

        World_cities[0] = "Houston";
        World_cities[1] = "Chicago";
        World_cities[2] = "Dallas";
        World_cities[3] = "London";
        World_cities[4] = "Dubai City";

        for (String currElement : World_cities) {
            System.out.println("The city in string array: " + currElement);
        } 
    }
}

Result:

The city in string array: Houston
The city in string array: Chicago
The city in string array: Dallas
The city in string array: London
The city in string array: Dubai City

Syntax of creating arrays

As shown in the above two examples, the arrays in Java can be created in different ways.  One way is to use the new keyword as follows:

numArray = new int[5];

In this way, the array is created with five elements. This line of code will allocate the memory of five elements whose data type is the integer.

Note that the array in Java may contain a fixed number of elements. Once created, it cannot be changed.  After creating this array, you may assign values to the array elements as follows:

numArray[0] = 5;

numArray[1] = 10;

numArray[2] = 15;

numArray[3] = 20;

numArray[4] = 25;

There, you may notice the array element index starts at 0. This is important while accessing the array elements as shown in the section below.

Creating array elements with shortcut syntax

You may also create array elements at the time of declaration. For example:

int[] numArray = { 5, 10, 15, 20, 25, 30, };

  • You have to specify the data type which is followed by the array name on the left side.
  • On the right side, the array element values are given in the curly braces.
  • Each value is separated by a comma.
  • In that way, the number of elements given in the array becomes the length of that array.

Declaring arrays of other data types

Similarly, you may create arrays by using any of the above ways for different data types. For example:

byte[] byteArray; //It will create an array of byte data type

short[]ShortsArray;

float[]FloatsArray;

String[] anArrayOfStrings; //used in one of the above example

How to access Java array elements

The array elements can be accessed by using the numeric index that starts at 0. You may use the array index in square brackets to access elements individually. For example:

numArray[0];

See the examples below for accessing a single element and using an enhanced for loop for accessing array elements.

An example of accessing an array element by index number

Using the same array as used in the second example in the above section (World cities array), I will access the element number 4 value by using its index as follows:

The Java code for accessing array element individually:

public class java_array {
    public static void main(String []args) {
        String[] World_cities = new String[5];

        World_cities[0] = "Houston";
        World_cities[1] = "Chicago";
        World_cities[2] = "Dallas";
        World_cities[3] = "London";
        World_cities[4] = "Dubai City";

        System.out.println("The city in element 4: " +  World_cities[4]);
    }
}

Output:

The city in element 4: Dubai City

You have already seen using the for loop for accessing the same array in above section. To learn more about enhanced for loop go to its chapter here.

An example of using a multi-dimensional array

The Java also supports multi-dimensional arrays. In this type of array, the array’s components are themselves arrays. The multi-dimensional arrays contain more than one column unlike single-dimensional arrays used in the above section.

The rows may vary in length in this type of array.

This is how a multidimensional array can be created:

int[ ][ ] NumArray = new int[3][3];

See this example where an array is created and then its elements are displayed by using the for loop.

Java multidimensional array example:

public class java_array {
    public static void main(String []args) {
                int[ ][ ] NumArray = new int[3][3];

                NumArray[0][0] = 5;
                NumArray[0][1] = 10;
                NumArray[0][2] = 15;
                NumArray[1][0] = 25;
                NumArray[1][1] = 30;
                NumArray[1][2] = 35;

                NumArray[2][0] = 45;
                NumArray[2][1] = 50;
                NumArray[2][2] = 55;   

                int x,y;
                for (x=0; x<3; x++){
                                for (y=0; y < 3; y++){
                                                System.out.println("Multidimensional array element:  " + NumArray[x][y] + " ");

                                }

                                System.out.println("");

               }

    }

}

Output:

Multidimensional array element: 5
Multidimensional array element: 10
Multidimensional array element: 15

Multidimensional array element: 25
Multidimensional array element: 30
Multidimensional array element: 35

Multidimensional array element: 45
Multidimensional array element: 50
Multidimensional array element: 55

A program using array length property

Getting the array length when the number of elements is unknown can be important in different scenarios.

Java provides length property that returns the total number of elements in the specified array. The returned value is an integer.

Have a look at this example where I have used the length property in a for loop to specify the condition for the maximum number of times the loop should iterate:

The array code with length property:

public class java_array {
    public static void main(String []args) {
        String[] World_cities = new String[5];

        World_cities[0] = "Auckland";
        World_cities[1] = "Sydney";
        World_cities[2] = "Dallas";
        World_cities[3] = "London";
        World_cities[4] = "Dubai City";


        System.out.println("Total length of array = " + World_cities.length + "\n"); 
        System.out.println("The array elements are:");

        for (int x=0;x<World_cities.length;x++){
            System.out.println(World_cities[x]);

         }
    }
}

Result:

Total length of array = 5
The array elements are:
Auckland
Sydney
Dallas
London
Dubai City

You see, by using the first System.out.println, the number of elements in the array is displayed by using this:

World_cities.length

After that, the same is used in the for loop for specifying the maximum counter.

A demo of arraycopy method

The arraycopy method of the array class can be used for copying the elements from one array to another. The “arraycopy” method takes a few parameters as described below:

Syntax:

Object copy_from_Array, int sourcePos, Object coptyTo_array, int coptyTo_array_pos, int length

See an example below to see the arraycopy method in action where an array of numbers is created with nine elements.

After that, a new array is created where elements will be copied after using the arraycopy method.

Finally, the destination array (after copying) elements are displayed:

The code of copying array elements:

public class java_array {
    public static void main(String []args) {

        int arrcopy_from[] = {5,10,15,20,25,30,35,40,45}; //Copy from or source array
        int arrcopy_to[] = new int[6]; //Destination array                           

        System.arraycopy(arrcopy_from, 1, arrcopy_to, 0, 6);  //This is where elements will be copied
        //Printing copied array elements

        System.out.println("The array elements after copying:" + " ");

        for (int i=0;i<arrcopy_to.length;i++){
                 System.out.println(arrcopy_to[i]);
          }
 }    
}

Output:

The array elements after copying:
10
15
20
25
30
35

You saw index 1 to 6 elements from the source array are copied to the destination array.

Summarizing arrays

In Java, arrays are useful and a powerful concept that can be used for storing multiple values of a similar type.

I have shown you a few examples after creating and declaring the array including numeric, string, and multidimensional arrays.

Let me summarize a few important points about Java arrays below:

  • The arrays may contain a fixed number of values.
  • The type of the values must be the same or an error will occur.
  • As you declare an array, its length can be specified. Once you have specified the length, it is fixed and cannot be changed.
  • The arrays in Java can be created in different ways.
  • You have to specify the type of array e.g. int, byte, short, String, etc.
  • The items or elements of an array are accessible by numeric index.
  • The index of the array starts at 0.
  • The array class comes up with a few useful methods and properties to manipulate arrays.
Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!