ARRAYS IN JAVA

ARRAY REFERENCE AND LENGTH

java-logo

When we declare and initialize an Array, as we know we are using a reference type. The Array myArray contains the reference pointing to the memory area where the array is located.

Reference type

If we now declare a second Array of type compatible with the first one and initialize it with the first Array, what we get is not the copy of the Array but myArray2 contains the value of the reference pointing to the same memory area as myArray.

myArray2

If we change myArray2, that is, in fact going to replace a value, myArray also changes.

Modifica

THE LENGTH ATTRIBUTE

All Arrays have a default instance attribute called length that tells us the number of elements contained in the Array.

Attributo length

Let’s see what happens for two-dimensional and irregular Arrays.

Array irregolare

THE FOR/EACH LOOP FOR ARRAYS

We use a for loop to display the elements of the Array myArray.

Ciclo for su array

In Java there is another For Loop designed for cases like this. el is the element taken from the Array myArray, which being an array of integers, this variable will also be of type int. This is followed by the colon and the object to be iterated. Within the loop el is a read-only variable.

For Each

Let us see in two-dimensional Arrays how the elements are scrolled.

Array Bidimensionali

INTRODUCTION TO VARARGS METHODS

We have seen so far that the parameters of a method are set at the declaration stage. However, there are cases where an arbitrary number of arguments to pass to a method is preferable.

varargs

Between the Data Type of the parameter and the arg parameter we inserted three dots. Arguments to the arg parameter are passed in the form of an Array with the type corresponding to the assigned Data Type.

Ciclo sul varargs

We build a test class and invoke the method.

Classe di test

We can introduce multiple parameters, however if there is a varargs parameter this must be unique and located at the end of the parameter list.

varargs e altri parametri

VARARGS METHODS OVERLOAD

Let’s see how to use varargs overload with a figure.

Overload

Let’s look at the test class.

Classe di test per overload

What happens if we disregard the signature? Which method will be invoked? You can find the answer in the downloadable code from GITHUB.

Varargs incorretto

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

GITHUB

EXECUTION OF THE EXAMPLE CODE

  • Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.

java -jar –enable-preview CourseJava.jar

  • Or run the main found in the file CorsoJava.java.