Introduction to Arrays in Java

This tutorial covers creating, accessing, initializing, inserting, searching and deleting arrays and their elements in Java. Examples are given for each of these actions to aid the reader in getting a hands-on experience.

Creating an Array

There are two kinds of data in Java: primitive types (such as int and double) and objects. In many programming languages (even object-oriented ones such as C++), arrays are primitive types, but in Java they’re treated as objects. Accordingly, you must use the new operator to create an array:

int[] intArray; // defines a reference to an array
intArray = new int[100]; // creates the array, and sets intArray to refer to it

Or you can use the equivalent single-statement approach:

int[] intArray = new int[100];

The [] operator is the sign to the compiler we’re naming an array object and not an ordinary variable. You can also use an alternative syntax for this operator, placing it after the name instead of the type:

int intArray[] = new int[100]; // alternative syntax

However, placing the [] after the int makes it clear that the [] is part of the type, not the name.

Because an array is an object, its name – intArray in the preceding code – is a reference to an array; it’s not the array itself. The array is stored at an address elsewhere in memory, and intArray holds only this address.

Arrays have a length field, which you can use to find the size (the number of elements) of an array:

int arrayLength = intArray.length; // find array size

As in most programming languages, you can’t change the size of an array after it’s been created.

Accessing Array Elements

Array elements are accessed using an index number in square brackets. This is similar to how other languages work:

temp = intArray[3]; // get contents of fourth element of array
intArray[7] = 66; // insert 66 into the eighth cell

Remember that in Java, as in C and C++, the first element is numbered 0, so that the indices in an array of 10 elements run from 0 to 9.

If you use an index that’s less than 0 or greater than the size of the array less 1, you’ll get the Array Index Out of Bounds runtime error.

Initialization

Unless you specify otherwise, an array of integers is automatically initialized to 0 when it’s created. Unlike C++, this is true even of arrays defined within a method (function). Say you create an array of objects like this:

autoData[] carArray = new autoData[4000];

Until the array elements are given explicit values, they contain the special null object. If you attempt to access an array element that contains null, you’ll get the runtime error Null Pointer Assignment. The moral is to make sure you assign something to an element before attempting to access it.

You can initialize an array of a primitive type to something besides 0 using this syntax:

int[] intArray = { 0, 3, 6, 9, 12, 15, 18, 21, 24, 27 };

Perhaps surprisingly, this single statement takes the place of both the reference declaration and the use of new to create the array. The numbers within the curly brackets are called the initialization list. The size of the array is determined by the number of values in this list.

An Array Example

Let’s look at some example programs that show how an array can be used. We’ll start with an old-fashioned procedural version and then show the equivalent object-oriented approach. The code below shows the old-fashioned version, called array.java:

// array.java
// demonstrates Java arrays
// to run this program: C>java arrayApp
////////////////////////////////////////////////////////////////
class ArrayApp
{
   public static void main(String[] args)
   {
      long[] arr; // reference to array
      arr = new long[100]; // make array
      int nElems = 0; // number of items
      int j; // loop counter
      long searchKey; // key of item to search for
      //--------------------------------------------------------------
      arr[0] = 77; // insert 10 items
      arr[1] = 99;
      arr[2] = 44;
      arr[3] = 55;
      arr[4] = 22;
      arr[5] = 88;
      arr[6] = 11;
      arr[7] = 00;
      arr[8] = 66;
      arr[9] = 33;
      nElems = 10; // now 10 items in array
      //--------------------------------------------------------------
      for(j=0; j<nElems; j++) // display items
      System.out.print(arr[j] + “ “);
      System.out.println(“”);
      //--------------------------------------------------------------
      searchKey = 66; // find item with key 66
      for(j=0; j<nElems; j++) // for each element,
      if(arr[j] == searchKey) // found item?
      break; // yes, exit before end
      if(j == nElems) // at the end?
      System.out.println(“Can’t find “ + searchKey); // yes
      else
      System.out.println(“Found “ + searchKey); // no
      //--------------------------------------------------------------
      searchKey = 55; // delete item with key 55
      for(j=0; j<nElems; j++) // look for it
      if(arr[j] == searchKey)
      break;
      for(int k=j; k<nElems-1; k++) // move higher ones down
      arr[k] = arr[k+1];
      nElems--; // decrement size
      //--------------------------------------------------------------
      for(j=0; j<nElems; j++) // display items
         System.out.print( arr[j] + “ “);
      System.out.println(“”);
   } // end main()
} // end class ArrayApp

In this program, we create an array called arr, place 10 data items (kids’ numbers) in it, search for the item with value 66 (the shortstop, Louisa), display all the items, remove the item with value 55 (Freddy, who had a dentist appointment), and then display the remaining 9 items. The output of the program looks like this:

77 99 44 55 22 88 11 0 66 33
Found 66
77 99 44 22 88 11 0 66 33

The data we’re storing in this array is type long. We use long to make it clearer that this is data; type int is used for index values. We’ve chosen a primitive type to simplify the coding. Generally, the items stored in a data structure consist of several fields, so they are represented by objects rather than primitive types. We’ll see such an example toward the end of this chapter.

Insertion

Inserting an item into the array is easy; we use the normal array syntax:

arr[0] = 77;

We also keep track of how many items we’ve inserted into the array with the nElems variable.

Searching

The searchKey variable holds the value we’re looking for. To search for an item, we step through the array, comparing searchKey with each element. If the loop variable j reaches the last occupied cell with no match being found, the value isn’t in the array. Appropriate messages are displayed: Found 66 or Can’t find 27.

Deletion

Deletion begins with a search for the specified item. For simplicity, we assume (perhaps rashly) that the item is present. When we find it, we move all the items with higher index values down one element to fill in the “hole” left by the deleted element, and we decrement nElems. In a real program, we would also take appropriate action if the item to be deleted could not be found.

Display

Displaying all the elements is straightforward: We step through the array, accessing each one with arr[j] and displaying it.

Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

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

Back To Top