ARRAYS IN JAVA
ARRAY REFERENCE AND LENGTH
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.
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.
If we change myArray2, that is, in fact going to replace a value, myArray also changes.
THE LENGTH ATTRIBUTE
All Arrays have a default instance attribute called length that tells us the number of elements contained in the Array.
Let’s see what happens for two-dimensional and irregular Arrays.
THE FOR/EACH LOOP FOR ARRAYS
We use a for loop to display the elements of the Array myArray.
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.
Let us see in two-dimensional Arrays how the elements are scrolled.
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.
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.
We build a test class and invoke the method.
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 METHODS OVERLOAD
Let’s see how to use varargs overload with a figure.
Let’s look at the test class.
What happens if we disregard the signature? Which method will be invoked? You can find the answer in the downloadable code from GITHUB.
LINKS TO PREVIOUS POSTS
LINK TO CODE ON 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.
Leave A Comment