Java - Arrays
An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.
Each item in an array is called an element, and each element is accessed by its numerical index. As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.
Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.
This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
dataType[] arrayRefVar; // preferred way. or dataType arrayRefVar[]; // works but not preferred way.
Note: The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
Example:
The following code snippets are examples of this syntax:
double[] myList; // preferred way. or double myList[]; // works but not preferred way.
Creating Arrays:
You can "create" an array by using the new operator with the following general syntax, however there are many different ways to create arrays in Java.
arrayRefVar = new dataType[arraySize];
The above statement does two things:
It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
assignment:
throwing away the old value of a variable and replacing it with a new one
initialization:
it's a special kind of assignment: the first. Before initialization objects have null value and primitive types have default values such as 0 or false. Can be done in conjunction with declaration.
declaration:
declaration states the type of a variable, along with its name. A variable can be declared only once. It is used by the compiler to help programmers avoid mistakes such as assigning string values to integer variables. Before reading or assigning a variable, that variable must have been declared.
Difference between Array Contructors & Array Initializers
- Array Constructor Syntax
Denoted by [] brackets
- Array Initializer Syntax
Denoted by {} brackets
int[] arrMyNumbers = new int[10] // Array Constructor Syntax int[] arrMyNumbers = {1, 2, 3, 4, 5, 6} // Array Initializer Syntax
1. Declaring an Array
Declaring an array variable.
int[] arrMyNumbers;
2.1 Declaring an Array with a fixed length in one statement
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement, as shown below. Remember that using this method the array will be initialized with null values
double[] arrCurrency = new double[10]; // "new double[10]" is an example of the array contructor syntax.
2.2 Declaring an Array with a fixed length in two statements
Declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in two statements, as shown below. Remember that using this method the array will be initialized with null values
double[] arrCurrency; arrCurrency = new double[10]; // "new double[10]" is an example of the array contructor syntax.
3.1 Declaring and Initializing an Array with Values in one statement
Declaring an array variable, and initializing the array with values done in one statement, as shown below. This is array initializer syntax, denoted/shown by the {} - curly brackets, and it can only be used on the right-hand-side when declaring a variable of array type. Example:
String[] names = {"Sanjay", "Jill", "Sipho", "Jack", "Yin"}; /* This is array initializer syntax, and it can only be used on the right-hand-side when declaring a variable of array type. */
3.2 Declaring and Initializing an Array with Values in two statements
Declaring an array variable, and initializing the array with values done in two seperate statements, as shown below. As mentioned above, the array initializer syntax is used again here, however if you're not on the right hand side of a variable declaration, an array constructor is used in conjunction with the array initializer syntax:
String[] names; names = new String[]{"Sanjay", "Jill", "Sipho", "Jack", "Yin"}; /* If you're not on the right hand side of a variable declaration, an array constructor is used instead (ah shown in the code above) */
The array elements are accessed through the index. Array indices are 0-based; that is, they start from 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10 elements of double type and assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
Processing Arrays:
When processing array elements, we often use either for loop or foreach loop because all of the elements in an array are of the same type and the size of the array is known.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } }
This would produce the following result:
1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5
The foreach Loops:
JDK 1.5 introduced a new for loop known as foreach loop or enhanced for loop, which enables you to traverse the complete array sequentially without using an index variable.
Example:
The following code displays all the elements in the array myList:
public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (double element: myList) { System.out.println(element); } } }
This would produce the following result:
1.9 2.9 3.4 3.5
Passing Arrays to Methods:
Just as you can pass primitive type values to methods, you can also pass arrays to methods. For example, the following method displays the elements in an int array:
public static void printArray(int[] array) { for (int i = 0; i < array.length; i++) { System.out.print(array[i] + " "); } }
You can invoke it by passing an array. For example, the following statement invokes the printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
Returning an Array from a Method:
A method may also return an array. For example, the method shown below returns an array that is the reversal of another array:
public static int[] reverse(int[] list) { int[] result = new int[list.length]; for (int i = 0, j = result.length - 1; i < list.length; i++, j--) { result[j] = list[i]; } return result; }
The Arrays Class:
The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.
SN | Methods with Description |
---|---|
1 | public static int binarySearch(Object[] a, Object key)
Searches the specified array of Object ( Byte, Int , double, etc.) for the specified value using the binary search algorithm. The array must be sorted prior to making this call. This returns index of the search key, if it is contained in the list; otherwise, (-(insertion point + 1). |
2 | public static boolean equals(long[] a, long[] a2)
Returns true if the two specified arrays of longs are equal to one another. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. This returns true if the two arrays are equal. Same method could be used by all other primitive data types (Byte, short, Int, etc.) |
3 | public static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints. Same method could be used by all other primitive data types (Byte, short, Int etc.) |
4 | public static void sort(Object[] a)
Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.) |