17 Java – Arrays

Arrays in Java

An array is a data structure that stores a fixed-size sequential collection of items. However, the items need to be of the same type. For instance, you may have score of 100 students after an exam. So instead of calling naming them score1, score2,…score100, you can just use an array to hold all the scores.

 

So in this lesson, we would cover the following

  1. How to declare an array
  2. How to create arrays
  3. Processing array elements
  4. Looping through array
  5. Array as Parameter
  6. Array as Return Type of Functions
  7. The Array Class in Java

 

 

1. How to declare an array

Similar to other variables, arrays  must be declared before use. However you need to keep in mind that arrays are reference types. Therefore the variable you declare would be a reference variable to an array.

 

So I provide a syntax for declaring an array below:

	//Method 1: square braces after data type
	int[] scores;
	
	//Method 2: square braces after variable
	char grades[];

 

  • In the first method, we declare an array scores, that would int values.
  • In the second method, we declare an array grades, that would hold char values

 

But I want you to take not of the two different methods. The method 1 is considered the preferred method.

 

 

2. How to create arrays

You can also create an array together with the array declaration. You simply need to provide the size of the array. That is the number of elements it would contain.

To do this use the syntax:

 

	//first: create an array of 100 ints
	int[] scores = new int[100];
	
	//second: create an array grades which empty
	char[] grades = {};
	
	//third: create an array grades2 and add 4 chars
	char[] grades2 = {'A','B','C','D'};

 

You can use any of the three methods above to create a new array

 

  • First: here we create an array the would hold 100 ints
  • Second: here we create an array but it is empty
  • Third: here we create an array of chars and initialize it to 4 chars

 

 

3. Processing array elements

You probably need to perform certain operations on an array. For example finding the sum of the elements of an array. Or maybe the average. It could also be that you want to count the elements. You can achieve this using loops.

It can be:

  • for loop
  • for…each loop

Let’s now write a program to perform some of these operations. This is given in Listing 1.0. I would recommend you try it yourself

 

public class ArrayDemo {

	public static void main(String[] args) {
		int[] scores = {89, 23, 45, 56, 67, 65, 59};
		
		//for loop to print all elements
		for(int i=0; i < scores.length; i++) 
		{
			System.out.println("Score  " + scores[i]);
		}
		
		
		//get sum of all elements
		int sum = 0;
		for(int i=0; i < scores.length; i++)  {
			sum = sum + scores[i];		
		}	
		System.out.println("The sum is " + sum);
		
		
		//Finding the max element
		int max = scores[0];
		for(int i=1; i < scores.length; i++) 
		{
			if(scores[i] > max) {
				max = scores[i];
			}			
		}
		System.out.println("Largest number " + max);	
	}		
}

Listing 1.0: Processing array, printing elements, finding sum and max.

 

As usual, I’ll remind you to make sure you run this code. At least, you start getting used to arrays in Java.

 

 

4. Looping Using Enhanced Loop

Although you now can loop through array elements, however, the for( : ) loop is a better kind of loop. We call it enhanced for loop. It also provide a shorter  an simpler.

Let’s now print the array elements using the enhanced for loop. You can find the code in Listing 1.1 below.

 

public class ArrayDemo {

	public static void main(String[] args) {
		int[] scores = {89, 23, 45, 56, 67, 65, 59};
		
		//print all elements using enhanced for loop
		for(int element: scores)
		{
			System.out.println("Score  " + element);
		}	
	}		
}

Listing 1.1: Printing array elements using enhanced for loop

 

 

5. Array as Parameter

Already, you know you can pass primitive types as parameters to function. Similarly, you can pass array as a parameter to a function. Take for example, you have a function called PrintArray. This function takes an array as parameter and prints out all the elements in the array.

So, to call this function, you need to pass an array to it as a parameter.

Lets write this function. See Listing 1.2

 

public class ArrayDemo {

	//Function that take array as parameter
	public static void PrintArray(int[] array) {
		
		for(int element: array){
			System.out.println("Score  " + element);
		}	
	}
	
	public static void main(String[] args) {
		
		int[] scores = {89, 23, 45, 56, 67, 65, 59};
		PrintArray(scores); //Call the PrintArray function
	}		
}

Listing 1.2: Passing array as parameter to function

 

 

6. Array as Return Type of Functions

You can also make array the return type of a function. Let’s just write a function to do this. So I have written it as you can see below in Listing 1.3.

 

//Function that returns an array
public static int[] Fives() {
	int[] fives = new int[20];
	int index = 0;
	
	for(int i=1; i <= 100; i++) {
		if(i%5 == 0) { 
			fives[index] = i;
			index = index + 1;
		}
	}
	
	return fives;
}

Listing 1.3: Function that returns an array

 

The function Fives() creates an array of multiples of five between 0 and 100. I recommend you combine it with the PrintArray function to see how it work.

 

 

7. The Array Class in Java

You can find a number of useful methods in the Arrays class. The Arrays class is in java.utils.Arrays package. So you can use these methods to perform various operation. Maybe you want to sort the array or search the array for a value.

I provide a list of 4 methods in the table below:

 

SN Method  and Description
1 public static int binarySearch(Object[] a, Object key)

This method searches the given array of Object  for the specified value using the binary search.

The array needs to be sorted before calling this method. the return value is the index of the search key, if it is in the list; otherwise, it returns ( – (insertion point + 1)).

2 public static boolean equals(double[] a, double[] a2)

This method returns true if the two given arrays of longs are equal. Two arrays are equal if both of the arrays have the same number of elements, and also all corresponding pairs of elements in both arrays are equal. True is returned if the two arrays are equal. This method is overloaded for primitive types as well

3 public static void fill(int[] a, int num)

This method assigns the given int value to each element of the specified array of ints. So all the elements of the array would contain just the same value, num.

4 public static void sort(Object[] a)

This method sorts the given array of objects in an ascending order. This is according to the natural ordering of the array elements.