ARRAYS IN JAVA
INTRODUCTION
Arrays allow us to represent lists of values with one or more dimensions. They are objects, and therefore follow the normal rules of reference types. The image below highlights the generic definition of a one-dimensional Array. For example, if we have to list a list of votes, we could declare n variables each representing one vote. However, this process is inconvenient and redundant. Arrays come to us for this purpose.
Type specifies the type of elements that will be contained in the Array. All elements must be of the same type. Then follows the name according to the normal identification rules. The pair of square brackets after the name lets the compiler know that we are declaring an Array. It follows the keyword new as for any other object, the type and number of elements contained in square brackets. Initializing an Array sets the data type to its default value, for the array declared in the figure above we have five zeros. For objects, the default value will be null.
Initialization can differ as we have seen before with objects.
INDEX AND LITERAL OF AN ARRAY
The index of an Array is an integer that represents a specific location within an Array and through which we access read and write. All Arrays in Java have an index; let us see a figure representing precisely an Array and its index.
To assign a value to the Array, simply specify the name of the Array and in square brackets the index.
The figure illustrates how to gain read access.
One of the ways to initialize an Array is a loop.
There is also another method for initializing a one-dimensional Array and that is the literal form. In this case there is no need to use the new operator; Java derives the number of elements based on what is specified in the curly bracket pair.
MULTIDIMENSIONAL ARRAYS
By far the most common form is two-dimensional Arrays, that is, consisting of two dimensions (rows and columns). Let’s see how they declare themselves.
The array has three elements (rows) each consists of five integer elements. Let’s see how to assign a value.
IRREGULAR ARRAYS
The second dimension does not strictly need to be declared; this is the case for a particular type of Arrays called Irregulars. Let’s see how to initialize an Irregular Array.
Then one Array at a time you go and specify the columns.
What we get is depicted in the figure.
Let us see how they are initialized through the literal form.
I give an example.
ALTERNATIVE DECLARATION OF AN ARRAY
In the second form we move the square brackets after the Data Type, similar speech for two-dimensional Arrays.
Let us see where this second form can be exploited from the figure shown.
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