This article is going to sum up the important points about arrays in the Java language, with code examples.

In general, array is a built-in data structure that holds a set of elements of the same type. Arrays are useful and indispensable in programming.

Here are the characteristics of arrays in Java:

  • Fixed length: Once an array is created, we cannot change its size. So consider using arrays when the numbers of elements are known and fixed. Otherwise, you should consider using another dynamic container such as ArrayList.
  • Fast access: It’s very fast to access any elements in an array (by index of the elements) in constant time: accessing the 1st element takes same time as accessing the last element. So performance is another factor when choosing arrays.
  • An array can hold primitives or objects.
  • An array of primitives stores values of the primitives.
  • An array of objects stores only the references to the objects.
  • In Java, the position of an element is specified by index which is zero-based. That means the first element is at index 0, the second element at index 1, and so on.
  • An array itself is actually an object.

 

1. Java Arrays declarations and initialization

Declare first and initialize later:

int [] numbers = new int[10];

This declares an array object to hold 10 integer numbers (primitive array).

When declaring an array of primitive type, remember these rules:

  • All numbers are initialized to zeroes by default. That means the above array numbers contain 10 numbers which are all zeroes, even we haven’t initialized the array yet.
  • Boolean elements are initialized to false by default.

Then we initialize values for each element of the array like this:

numbers[0] = 10;
numbers[1] = 500;
numbers[2] = 1000;
...

The following statement declares an array of String objects:

String[] names = new String[5];

This array holds 5 String objects. And by default, all elements of Object type are initialized to null.

NOTE: In Java, you can place the brackets [] either after the type or after the variable name. Hence these declarations are both correct:

String[] names = new String[5];
String titles[] = new String[10];

However, it’s recommended to use the [] after the type for readability: You can easily realize this is an array of Strings, or that is an array of integer numbers.

You can also declare and initialize elements of an array in one statement. For example:

int[]  numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

This creates an array with 10 integer numbers which are initialized up declaration. This is a handy shortcut for declaring arrays whose elements are already known at compile time.

This statement declares and initializes an array of Strings:

String[] columnNames = {“No”, “Name”, “Email”, “Address”};

 

2. Java Multi-dimensional arrays

We can create an array of arrays (2-dimension array). For instance:

float[][] matrix = new float[5][3];

This creates a 2D array with is equivalent to a matrix of 5 rows and 3 columns.

Another example:

String[][] sampleData = {
		{"a", "b", "c", "d"},
		{"e", "f", "g", "h"},					
		{"i", "j", "k", "l"},
		{"m", "n", "o", "p"},				
	};

This creates a 4x4 array and initializes all the elements.

We can also create a 3D array, 4D array, etc using the same technique. 

3. Arrays Manipulation in Java

We access elements in the array by index (remember 0-based):

String firstColumn = columnNames[0];

This statement takes value of the first element in the String array columnNamesand assigns it to the variable firstColumn.

The following statement illustrates accessing an element in a 2D array:

String[] firstRow = sampleData[0];

This gets the first element in the sampleData array, which returns an array.

The following statement takes the element at 3rd row and 2nd column in the above 2D array:

String letter = sampleData[4][3];

And these examples show how to assign values to elements in arrays:

columnNames[2] = “Phone;
columnNames[4] = new String(“City”);
numbers[4] = 1024;
sampleData[4][2] = “xyz”;

A common operation is iterating an array using a loop statement like the for statement. The following example uses the for loop to iterate over all elements in an array of integer numbers, and prints value of each element:

int[]  numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

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

 

For arrays of objects you can use the for eachsyntax to iterate. For example:

String[] nameList = {"Tom", "Mary", "Peter", "John", "Adam", "Justin"};

for (String aName : nameList) {
	System.out.println(aName);
}

 

Besides the fundamental operations like getting and setting, Java provides various functions to manipulate arrays in the Arrays class.

The Arrays is a utility class which can be found in the java.util package. Here are some noteworthy methods it provides:

  • asList(): returns a fixed-size list backed by an array.
  • binarySearch(): searches for a specific value in an array. Returns the index of the element if found, or -1 if not found. Note that the array must be sorted first.
  • copyOf(): copies a portion of the specified array to a new one.
  • copyOfRange(): copies a specified range of an array to a new one.
  • equals(): compares two arrays to determine if they are equal or not.
  • fill(): fills same values to all or some elements in an array.
  • sort(): sorts an array into ascending order.
  • And other methods you can find in the Arrays class Javadoc.

In addition, the System.arraycopy() is an efficient method for copying elements from one array to another. Remember using this method instead of writing your own procedure because this method is very efficient.

So far I have walked you through a tour of arrays in Java. Here’s the summary for today:

  • An array is an object.
  • Elements in an array are accessed by index (0-based).
  • Advantage of array: very fast access to elements.
  • Disadvantage of array: fixed length, not appropriate if a dynamic container is required.
  • The java.util.Arrays class provides useful utility methods for working with arrays such as filling, searching and sorting.
  • The System.arraycopy() method provides an efficient mechanism for copying elements from one array to another.

API References:

 

Related Array Tutorials:

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment