Arrays in Java IV: Manipulating Individual Elements

Many a times you want to operate on individual elements of an array. For example, you may want to apply some operators on some, but not all elements of the array. We have already seen how declare and initialize Java arrays.  In this lesson we learn how to operate on array elements.

You can initialize, modify, access and delete individual elements. In the next section we will look at code that demonstrates each of these operations.

Note that removal of an element has limited scope because length of an array is always fixed. Depending on the problem scenario, a delete operation may just put a null or an empty object at the location to be deleted.

A Java array knows its size and exposes it using the length property. Since every java array knows its size, segmentation fault cannot occur. A segmentation fault occurs when there is an illegal access to memory. Java’s security features prevent access of memory beyond the array limits.

Example of Array Element Manipulation

Let’s look at the code below which accesses, modifies and deletes (which is nothing but a modify operation) individual elements of array –

The above program when executed, gives the following output

Manipulating Elements of Java Array via Copy of Reference

It is possible to manipulate individual elements of an array via the array name or through a copy of the reference to the array. Consider the code below

Note that the following statement does not reserve any memory. It is merely a declaration

And the following statement just creates a new name for the memory locations created earlier.

Any changes to the array made through arr2 variable is visible via arr variable and vice versa

As you have seen in the example above accessing and manipulating individual element is possible but is very cumbersome. Therefore, in the next and the fifth on arrays we discuss iteration mechanisms.

Leave a comment

Your email address will not be published. Required fields are marked *