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, number2, .. and number99, we can declare one array variable such as numbers and use numbers[0], numbers[1], .. and numbers[99] to represent individual variables.
To use an array, we must declare a variable to reference the array and specify the type of array the variable can reference.
The syntax for declaring an array variable:
datatype[] arrayVar;
Example:
double[] numbers;
After an array variable is declared, we can create an array by using the new operator with the following syntax:
arrayVar = new dataType[arraySize];
Example:
numbers = new double[10];
The sub-section (1) and (2) does two things:
(1) it creates an array using new dataType[arraySize];
(2) it assigns the reference of the newly created array to the variable arrayVar.
However, declaring an array variable, creating an array, and assigning the reference of the array to the variable can be combined in one statement:
datatype[] arrayVar; // declare an array
arrayVar = new dataType[arraySize]; // create an array
Both statements can be combined:
// declare and create an array
dataType[] arrayVar = new dataType[arraySize];
Example:
double[] numbers = new double[10];
This statement declares an array variable, numbers, creates an array of ten elements of double type, and assigns its reference to numbers.
Note: Unlike declarations for primitive data type variables, the declaration of an array variable does not allocate any space in memory for the array. It creates only a storage location for the reference to an array. If a variable does not contain a reference to an array, the value of the variable is null. We cannot assign elements to an array unless it has already been created.
To assign values to the elements, use the syntax:
arrayVar[index] = value;
Example:
numbers[0] = 5.6;
numbers[1] = 4.3;
numbers[2] = 2.2;
numbers[3] = 3.1;
numbers[4] = 2.2;
numbers[5] = 8.1;
numbers[6] = 1.3;
numbers[7] = 9.1;
numbers[8] = 5.4;
numbers[9] = 3.7;
The array is pictured as:
When declare an array, we must specify the size of the array.
The size of an array cannot be changed after the array is created.
Example:
double[] numbers = new double[10];
The size of array numbers is 10.
When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, '\u0000' for char types, and false for boolean types.
The array elements are accessed through the index. The index start from 0 to arraySize-1.
number 0, 1, 2, .. 9 are called index (start from 0, end with 9 and total elements is 10).
numbers[9] represents the last element in the array numbers.
Example:
numbers[2] = numbers[0] + numbers[7];
In the above statements, value in numbers[0] is add with value numbers[7] and store/assign in numbers[2]. Since numbers[0] is 5.6 and numbers[7]is 9.1, thus numbers[2] becomes 14.7.
Array initializers, which combines in one statement declaring an array, creating an array, and initializing, using the following syntax:
dataType[] arrayVar = {value0, value1, .. , value9};
for example:
double[] numbers = {5.6, 4.3, 1.9, 2.7};
// no need to state the size of an array
The above statement declares, creates and initializes the array numbers with four elements, which is equivalent to the statements shown below:
double[] numbers = new double[4];
numbers[0] = 5.6;
numbers[1] = 4.3;
numbers[2] = 1.9;
numbers[3] = 2.7;
When processing array elements, we can use a for loop, because:
All of the elements in an array are of the same type. They are evenly processed in the same fashion by repeatedly using a loop.
Since the size of the array is known, it is natural to use a for loop.
Let say, we declare numbers as an array of size 10.
int[] numbers = new int[10];
1. Initializing arrays.
The following loop initializes the array numbers with 0.
for (int i=0; i<numbers.length; i++)
numbers[i] = 0;
Note: In the above statements, method length is used to obtain the size of an array.
2. Read and store data in arrays.
The following loop will read the data using the statement input.nextInt() and store in array numbers.
Scanner input = new Scanner(System.in);
for (int i=0; i<numbers.length; i++)
numbers[i] = input.nextInt();
3. Print an array.
Print each element in the array using a loop.
for (int i=0; i<numbers.length; i++)
System.out.println(numbers[i] + " ");
4. Summing all elements.
Use a variable named total to store the sum. Initially total is 0 and then add each element in the array to total using loop.
int total = 0; // declare and initialize variable total
for (int i=0; i<numbers.length; i++)
total += numbers[i];
5. Finding the largest element.
Use a variable named max to store the largest element. Initialized max as numbers[0]. To find the largest element in the array numbers, compare each element in numbers with max, and update max if the element is greater than max.
int max = numbers[0]; // declare and initialize variable max
for (int i=0; i<numbers.length; i++){
if (numbers[i] > max)
max = numbers[i];
}
6. Finding the index of largest element.
Same as no.5 in the above. But this time we want to know which element is the highest value instead of what number is the highest.
int max = numbers[0];
int indexOfMax = 0;
for (int i=0; i<numbers.length; i++){
if (numbers[i] > max) {
max = numbers[i];
indexOfMax = i;
}
}
7. Shifting elements.
The following code segments will shift the elements one position to the left and fill the last element with the first element.
int temp = numbers[0];
for (int i=0; i<numbers.length; i++)
numbers[i-1] = numbers[i];
numbers[numbers.length -1] = temp;
Write a program that reads 10 integers, store as an array, and print the array.
In this exercise, we need to:
declare and create an array of size 10
read an array using for loop
print an array using for loop
Let say our array name is list. We need to declare and create an array name list with size 10. The array type is integer.
int[] list = new int[10]; // declare and create an array of size 10
Scanner sc= new Scanner(System.in);
for (int i=0; i<numbers.length; i++)
list[i] = sc.nextInt(); // read the array
for (int i=0; i<numbers.length; i++)
System.out.println(list[i] + " "); // print the array
Let say we have two arrays; array1 and array2, and we want to copy the content of array1 into array2.
int[] array1 = {2, 3, 1, 4, 6}; // array1 has size 5
int[] array2 = new int[array1.length]; // array2 has same length with array1
Use for loop to copy individual elements one by one. We cannot use assignment statements to copy arrays because it will not copy the elements of the array but only copy the reference of the array.
for (int i=0; i<array1.length; i++)
array2[i] = array1[i];
Another approach is to use the arraycopy method defined in the java.lang.System class. The syntax for arraycopy is shown below:
arraycopy(sourceArray, scr_pos, targetArray, tar_pos, length)
So, to copy the content of array1 into array2 using this method:
arraycopy(array1, 0, array2, 0, array1.length);
Searching is the process of looking for a specific element in an array. For example, searching for a certain number in a list of integers.
The following algorithm is called a linear search approach that compares the key element sequentially with each element in the array. It continues to do so until the key matches an element in the array or the array is exhausted without a match being found. If a match is made, the linear search returns the index of the element in the array that matches the key. If no match is found, the search returns -1. The search method is as following:
public class search{
public static int search(int[] list, int key){
for (int i=0; i<list.length; i++) {
if (key == list[i])
return i;
}
return -1;
}
}
There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:
Syntax:
for (type variable : arrayname) {
...
}
Example:
public class Example {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
Output:
Volvo
BMW
Ford
Mazda
Example:
public class Example {
public static void main(String[] args) {
int[] arrayA = {19, 2, 35};
for(int i: arrayA)
System.out.println(i);
}
}
Output:
19
2
35
Example:
public class Example {
public static void main(String[] args) {
int[] arrayA = {19, 2, 35};
java.util.Arrays.sort(arrayA);
for(int i: arrayA)
System.out.println(i);
}
}
Output:
2
19
35
Write a program to determine if two lists are identical or not. For example, the first list is 1,2,3,4,5,6 and the second list is 1,2,2,4,5,6. These two lists are not identical because the third number is not the same.
In this exercise, we need to:
declare and create two arrays of size 10; list and list2
read both arrays
compare both arrays to determine either both arrays are identical or not.
import java.util.Scanner;
public class IdenticalArray {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// declare and create array1
int[] list = new int[10];
// read an array1
for (int i=0; i<list.length; i++){
list[i] = sc.nextInt();
}
// declare and create array2
int[] list2 = new int[10];
// read an array2
for (int i=0; i<list.length; i++){
list2[i] = sc.nextInt();
}
// determine either identical or not
boolean flag = true;
for (int i=0; i<list.length; i++){
if(list[i] == list2[i])
flag = true;
else
flag = false;
}
if (flag == true)
System.out.println("identical");
else
System.out.println("no");
}
}
Write a program to determine the highest number and the number of it occurrences.
public class NumberMax {
public static void main(String [] a) {
Scanner sc = new Scanner(System.in);
int[] list = new int[10]; //declare & create array
for (int x=0; x < list.length; x++){
list[x] = sc.nextInt(); //read the integer and store in array
}
//find the max in the array
int max = list[0];
for (int x=0; x < list.length; x++){
if (list[x] > max)
max = list[x];
}
//find the occurrence of max number
int qty = 0;
for (int x=0; x < list.length; x++){
if (list[x] == max)
qty++;
}
//print the output
System.out.println("Max number is " + max +" and occurs " + qty + "times ");
}
}
Let say the input is:
8 7 2 3 6 7 8 10 8 10
Thus the output will be:
Max number is 10 and occurs 2times
Write a program to determine the average.
public class FindAverage{
public static void main(String [] a) {
Scanner sc = new Scanner(System.in);
//read the number of data (size of array)
int numData = sc.nextInt();
//declare & create array
int[] list = new int[numData];
//read the integer and store in array
for (int x=0; x < numData; x++){
list[x] = sc.nextInt();
}
//find sum
double sum = 0;
for (int x=0; x < list.length; x++){
sum += list[x];
}
DecimalFormat df = new DecimalFormat("0.00");
double aver = sum/numData;
//print the output
System.out.println("The average is " + df.format(aver));
}
}
Let say the input is:
8 7 2 3 6 7 8 10 8 10
Then the output will be:
The average is 6.38