Array in Java: Areas of use and built-in methods


Keywords: array, for-each loop, enhanced for loop, java.util.Arrays

Array Java programming

This article will demonstrate some features and how we can use an array to store and process our data. We will see several different examples of what we can use an array for, and demonstrate that there are several properties of an array in Java that make them easy to use.

How use an array in Java?

As we saw when we introduced what an array is, we can use, read and edit each element in the array using the array indexes. We write the name of the array followed by the index in square brackets.

Assign value from array to variable

Let’s take a shorter illustrative example and create an array that we call arrEx and assign a pair of values.

public class Example{
   public static void main(String[] args) {
      int [] arrEx = {22, 8, 97, 3};
   }
}

Furthermore, if we want to use one of the elements we saved in arrEx and assign it to a variable, we simply write

public class Example{
   public static void main(String[] args) {
      int [] arrEx = {22, 8, 97, 3};

      int varEx = arrEx[2];
   }
}

That will be equal to

Array Example Java

Figure 1: Assign value stored in array to variable in Java

Finally, if we print the value of the variable varEx:

public class Example{
   public static void main(String[] args) {
      int [] arrEx = {22, 8, 97, 3};
      int varEx = arrEx[2];

      System.out.println("The value in the array arrEx on index 2 is: " + varEx); 
   }
}

We get the result

The value in the array arrEx on index 2 is: 97

Length of array in Java

If we want to know how large an array is, we write the name of the array we are working with, followed by .length. The built-in length method specifies the number of elements assigned and not the inserted value. If we have the same array as before, the one we named arrEx, and want to know how many elements it contains, we write:

public class Example{
   public static void main(String[] args) {
      int [] arrEx = {22, 8, 97, 3};
      int lenArr = arrEx.length; 

      System.out.println("The length of arrEx is: " + lenArr); 
   }
}

Array length Java programming

Figure 2: Length to get the number of elements in array

We get the result

The length of arrEx is: 4

Pay attention to the fact the length of the array will be greater than the index since the index always starts at 0, and the length is calculated as the number of elements. For example, in arrEx above, the last index is three, and the length is four.

Assignment does not provide a copy, but a reference to the same array

An assignment references the same array and not a copy; what does that really mean? When we assign the content from one array to another, both arrays will point to the same element. If we have the same arrEx that we used before and write

public class Example{
   public static void main(String[] args) {
      int [] arrEx = {22, 8, 97, 3};
     
      int [] arrExTwo = arrEx; 
   }
}

Will result in

Array Assignment copy Java programming

Figure 3: Assignment provides a reference to the same array

Furthermore, this means that if we write

public class Example{
   public static void main(String[] args) {
      int [] arrEx = {22, 8, 97, 3};
     
      int [] arrExTwo = arrEx; 
      arrExTwo[3] = 45; 

      System.out.println("Value on index 3 in arrEx: " + arrEx[3]); 
   }
}

That value of that element will also change for arrEx because they point to the same element. Let’s demonstrate the result

Value on index 3 in arrEx: 45

Examples of using an array in Java

We will now look at a couple of examples of how we can work with an array. For example, some classic use areas are searching through an array or summing all the values in an array.

Example 1: Summarize values in array in Java

As we saw, when looking at the for-each loop in the previous article, we can easily sum the elements in an array. We need to create a variable to save all values, in this example named total, and then run through the array and summarise the values.

public class ExampleOne {
   public static void main(String[] args) {

      int total = 0; 
      int[] arrEx = {22 , 8, 97, 3}; 

      for (int element : arrEx){
         total = total + element; 
      }

      // Result of total
      System.out.println("The sum of the values in arrEx = " + total);
   }
}

That will result in

The sum of the values in arrEx = 130

Example 2: Searching an array in Java

If we want to search through an array, for example, we are looking for a particular element’s position to be able to replace it. In this case, we will use a while loop, where we set the condition that the position must be within our array (of course) and that the value must not be found. When any of those conditions are not met, the while loop ends.

To see if the element at that position in the array equals the searched value, we will use an if statement. If the value does not match, the position variable will increase by one to check the next position in our array.

public class ExampleTwo {
   public static void main(String[] args) {

      int [] field = {5, 6, 33, 54, 77, 87, 32, 78, 98};

      // The value we are looking for 
      int searched = 78;

      // Save the position (index)
      int pos = 0;         

      boolean found = false; 

      while (pos < field.length && !found) {
         if (field[pos] == searched){
            // We have found the value
            found = true;   
         }
         else{ 
            // Increase the position variable by one
            pos++;   
         }
      }

      // If we want to print the position
      if (found == true){ 
         System.out.println("Value " + searched + " was found on index: " + pos); 
      }

      // Or if we did not find the value
      else{
         System.out.println("The value could not be found in the array");
      }
   }
}

In conclusion, the result if we run the program will be:

Value 78 was found on index: 7

Example 3: Find the largest and smallest value of an element in an array

In this example, we will search for the largest and smallest value in an array. We will use a for loop that processes the array we are working with and then use two variables that we named largest and smallest. We will start by assigning the value contained in the first element in arrEx to both largest and smallest.

public class ExampleThree {
   public static void main(String[] args) {

      int[] arrEx = {22 , 31, 8, 14, 57, 3, 81, 79, 4, 80}; 

      // Assign value on index 0
      int largest  = arrEx[0]; 
      int smallest = largest; 

      for (int i = 0; i < arrEx.length; i++){

         // If value larger than current largest value
         if (arrEx[i] > largest){
            largest = arrEx[i]; 
         }

         // Or, if value is smaller than the current smallest value
         else if (arrEx [i] < smallest){
            smallest = arrEx[i];
         }
      }

      // Display the result
      System.out.println("Largest value in arrEx is: " + largest +
      "\nSmallest value in arrEx is: " + smallest);
   }
}

Finally, the result if we run the code above will be:

Largest value in arrEx is: 81
Smallest value in arrEx is: 3

Example 4: Print the reverse order for array in Java

In this example, we will use an array that contains several different names (Strings) and what we are going to do is print them in reverse order in a table starting with 1. We will use a for loop to process the array

public class ExampleThree {
   public static void main(String[] args) {

      String[] names = {"Eric", "Carolin", "Tom", 
         "Gustav", "Amanda", "Maria", "Rebecca", "Carl"};

      for (int i = 0; i < names.length; i++){
         System.out.println(i+1 + ". " + names[names.length - 1 - i]);
      }
   }
}

Pay attention to that we write names[names.length – 1 – i] inside the for-loop. This is because the length of the array will be greater than the index since the index always starts at 0, and the length is calculated as the number of elements. Therefore, we need to reduce that by one so we are not ending up outside of our array. names[names.length – 1 – i] lets us begin on the last element in arrEx, and then increase as we go to the array’s start.

In conclusion, the result from the program above will be:

1. Carl
2. Rebecca
3. Maria
4. Amanda
5. Gustav
6. Tom
7. Carolin
8. Eric

Example 5: Create methods to compare values in an array

Let us now take an example where we use methods to extract the largest, respectively smallest, value from an array in a similar way as in example 3.

  • We then want to compare whether the largest and smallest value together is greater or less than the sum of all the other values.
  • To our help, we will create two methods, smallIndex and largIndex, which will take an array as an input parameter and return the index for the smallest and largest value in that array.
  • We will thus work with indexes for the elements, and we do this to demonstrate how it works with indexes in an array.

First, we create a method that returns the index of the smallest value in an array

public static int smallIndex (int [] a){

    int smallIndex = 0;
    int smallVal = a[0];

    for(int i = 0; i < a.length; i++){
        if( smallVal > a[i]){
            smallVal = a[i];
            smallIndex = i;
        }
    }
    return smallIndex;
}

Then we create a method that returns the index of the largest value in an array

public static int largIndex (int [] a){

    int largIndex = 0;
    int largVal = 0;

    for(int i = 0; i < a.length; i++){
        if( a[i] > largVal){
            largVal = a[i];
            largIndex = i;
        }
    }
    return largIndex;
}

Finally, we use the two methods and a for loop that sums the values in our array, without the values of the indexes that contain the largest and smallest value.

public static void main(String args[]) {
    int[] arrEx = {22 , 31, 8, 14, 57, 3, 81, 79, 4, 80};
    int small = smallIndex(arrEx);
    int large = largIndex(arrEx);
    int sum = 0;

    for (int i = 0; i < arrEx.length; i++){
        if (i != small && i != large){
            sum = sum + arrEx[i];
        }
    }

    if (sum > (arrEx[small] + arrEx[large])){
        System.out.println("The total without the smallest and largest value is: " + sum +
        "\n which is GREATER than the smallest and largest value together, that is: " 
        + (arrEx[small] + arrEx[large]));
        }

    else{
        System.out.println("The total without the smallest and largest value is: " + sum +
        "\n which is SMALLER than the minimum and maximum value together, that is: " 
        + (arrEx[small] + arrEx[large]));
    }
}

To conclude, the result from the program above will be

The total without the smallest and largest value is: 295
which is GREATER than the smallest and largest value together, that is: 84

java.util.Arrays class: Built-in methods for working with an array

The java.util.Arrays class contains a variety of methods for modifying and working with an array, such as sorting or searching an array. But before we can use the methods below, we need to import the class, which we do easily by entering import java.util.Arrays;

The methods in the class java.util.Arrays are good to know, or rather, it is good to know that they exist. With that said, we do not suggest that you sit and study the methods; rather pay attention to the fact that there are built-in methods in Java that you can use when working with an array.

java.util.Arrays: Some of the most common methods

Furthermore, but let’s look at some of the most common methods found in java.util.Arrays so you can get an idea of what they can do. Note that all the methods below can be used for all primitive data types.

  • Arrays.binarySearch(datatyp [] a, datatyp key)
    Searches for a specific value in an array. Returns the element index if it exists or -1 if it is not found.
  • Arrays.equals(datatyp [] a, datatyp[] b)
    Returns true if the two specified arrays are equal. Two arrays are considered equal to each other if both contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal.
  • Arrays.fill(datatyp[] a, datatyp val)
    Assigns the specified value, val, to each element in the specified array. Note that the data type for the array and the variable must, of course, match because we can only store data types of the same type in an array.
  • Arrays.sort(datatyp[] a)
    Sorts the specified array in ascending order, according to its natural order.
  • Arrays.toString(datatyp [] a)
    Returns the contents of the specified array as a text string, i.e. of data type String.

Finally, if you want to read more about the class java.util.Arrays and see a more detailed list and examples of how it is used; you can do so on Oracle’s page by clicking here

Common error when using array in Java

Perhaps the most common mistake when using an array is trying to access an element that does not exist. Let’s take a simple example, and it will be easier to understand what we mean. We create an array, named field, and then intend to save a value our array field.

public class ExampleError {
   public static void main(String[] args) {

      int [] field = new int [10]; 
      int[10] = 5;
   }
}

This gives the error message java.lang.ArrayIndexOutOfBoundsException, since our array field has 10 elements, with an index range from 0 to 9. As we saw earlier, when we went through how to calculate the length of an array, the length of the array will be one greater than the index. The length of the array will be greater than the index since the index always starts at 0, and the length is calculated as the number of elements.

Summary: Array areas of use and built-in methods

We can use an array to store and process data. We can use, read, and edit each element in the array using indexes by simply writing the array’s name followed by the index in square brackets. In addition to using loops, usually the for loop, to work with an array, there are also built-in methods in the java.util.Arrays class.

If we want to know how large an array is, we write the name of the array we are working with, followed by .length. The built-in length method specifies the number of elements assigned and not the inserted value. Additionally, remember that the length of the array will be one greater than the index so you are not trying to access an element out of bounds.

FAQ: Array in Java

How do you find out how long an array is?

This is easily done by using the built-in method length. You use it by typing the name of the method followed by a dot length.

Do I have to use a for loop to search an array?

No, it is at least as good to use a while loop or a do-while loop. However, the for loop may be preferred as it is a counting loop, and an array is a predetermined collection of data that the loop is processing.


What does the java.lang.ArrayIndexOutOfBoundsException error message mean?

This means that your program tried to reach an element that is outside the array you are working with. For example, if an array has 10 elements, the index will be from 0 to 9. When calculating the length of an array, the length of the array will be one greater than the index. The length of the array will be greater than the index since the index always starts at 0, and the length is calculated as the number of elements.