Arrays and their usage in Java programs

We might have come across the term array in the past, so let's see what arrays are with an explanation and an example.

An array is a container that stores multiple values of the same data type.

In the following example, we will see what a container is, how to define that container, and how we can store values in them.

If we want to work with arrays, we declare them by allocating some space for them using the following code:

int a[] = new int[];

The new keyword basically allocates memory for a value in this array. The square brackets mean that we are adding multiple values into the brackets, [] indicates the term for the array. To define an array, we have to create space for the multiple values that we will be storing in it. In this example, we have five integer values that we are planning to store in the array, which is why we have specified the array data type as an integer, and the number of variables to be added is given in the square brackets:

int a[] = new int[5];

As we observed in Chapter 3, Handling Strings and Their Functions in Java, if the values were strings, we would specify the array data type as String.

We have declared an array and allocated memory for the values, now we need to pass those values. The first value will be placed in index 0, the second in index 1, and so on for all five values. Index naming starts from the 0 index, so the first value will be assigned to the 0 index. This means that we actually initialized values in the array. Now the a array holds all the values that we assign to it. For our example, we declare any random values for the array.

Now let's retrieve the values from the array. To do so, we create a for loop by typing the following code in the main class after declaring the values of the array and leave a print statement after that:

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

Our starting point has been set at index 0 and the limit has been set to the length of the array. Take a look at the i<a.length code, length is a method that actually returns the size of the array.

On running the code we see that all the values assigned to the array are printed one after the other. In the next section, we will see a simpler way to declare and initialize all the array values.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.131.178