WALT: In this unit you will learn how to use one-dimensional arrays in Java. You should be familiar with 1D arrays from Python and arrays in Java work in a similar fashion.
Just to recap: arrays are data structures that can, unlike primitive variables, hold more than piece of data at once - so for instance an array (set) of integers, doubles, booleans, or even Strings and other types of objects. In some programming languages, such as Scratch and App Creator, arrays are called lists.
To represent multiple pieces of related data in one variable (such as exam scores, student names, account numbers, etc.)
The array size must be set when creating the array - it cannot be modified later on. A block of memory is then reserved for the array.
All primitives as well as object references (not objects themselves)
Take a look at the following example:
int[] testScores = new int[5];
In this line of code we created an array of integers that has size 5 (i.e. it can hold up to 5 integers). Alternatively, you can first declare an array and then initialize it:
1 int[] testScores;
2 testScores = new int[5];
In line 1 we declared an array of integers but no memory has been allocated yet.
In the second line we initialized the array by calling its constructor with parameter 5 - telling the constructor to allocate enough memory to hold five integers.
Does the keyword "new
" look familiar? You have used it to call the constructor to initialize an object of some class - such as Student s1 = new Student("Peter Smith");
.
When you compare the array creation and initialization example with the Student object example, you can tell they are very similar. With arrays, the class name is the data type desired followed by []
. The only difference is that the constructor takes in the parameter inside the square brackets instead of round brackets, like it is with other classes.
By now, you can probably tell that arrays in Java are special kinds of objects.
The general formula for array declaration and initialization would be as follows:
dataType[] arrayName = new dataType[size];
When initializing an array using the new
keyword, the following values are used as defaults:
0
0.0
false
null
(no objects are created and thus there is no reference to the object)Example:
The following line of code will create an array with the following default values:
double temperature[] = new double[4];
String names[] = new String[3];
An alternative way to declare and initialize an array with specific (not the default) data is by using the so called initializer list. See the example below:
This will cause the following in the memory:
String[] programmers={"Aldyiar","Andy","Anthony"};
int scores[] = {55,73,98,64,80};
Notice that in the first example, the array slots do not hold the actual text but only references to String
objects that hold the actual text. The individual String
objects are created and loaded with the corresponding data when using an initializer list.
The length of an array (i.e. how many items of data it can hold) is its instance variable (a public final int
) that can be read as follows: arrayName.length
Using the programmers
array example above, the following line of code would display 3
.
System.out.println(programmers.length));
This property is particularly useful when trying to traverse an array.
To read or modify array items we use the so called index number (see the tables above) which is inside the square brackets. Notice that index numbers always start from zero, not one. For instance, in order to display the fifth score (80
) from the scores[]
array above, I'd use the following code:
System.out.println(scores[4]);
A common mistake is when you forget to count from 0
, not 1
- in our example you'd, for instance, write scores[5]
to access the 5th element in the array. This would cause an ArrayIndexOutOfBoundsException
being thrown as it would try to read the 6th element of the array which doesn't exist. Index numbers must always be between 0
and one less than the number of elements in the array (arrayName.length-1
). So for the scores[] array, the index number must be between 0
and 4
as the array length is 5
.
You can modify array elements using index numbers as well. Examples:
scores[0] =47;
programmers[1]="Anton";
To display the last item in an array (regardless of its length), I'd use the following code:
arrayName[arrayName.length-1];
So, the code below will display "Anthony
":
System.out.println(programmers[programmers-1]);
As you can see, we have been using a variable as an index — you can do this as long the variable data type is an int
.
for
-loop or a while
-loop.ArrayIndexOutOfBoundsException
being thrown.The following example demonstrates how to traverse and print all elements of an array using the for-loop iterator variable as index number:
1 String [] names = {"Tomas", "Wonkyu", "Soosan", "Anton"};
2 for (int i=0; i<names.length; i++)
3 System.out.println(names[i]);
A method can receive an array as an argument. Consider the following method that takes in an array of Strings and prints each array value on a separate page alongside its index number:
1 public static void printArray(String[] myArray)
2 {
3 for (i=0;i<myArray.length;i++)
4 System.out.println("Index number: "+i+" value: "+myArray[i];
5 }
You must remember that when passing an array as an argument - you are accessing the array directly , so if you are modifying any values in the array inside the method, it indeed gets saved in the original array that was passed as an argument (as what is really passed on is the reference to the original array object, not a copy of the individual values in the array). This is different from passing primitives as parameters where a copy of the original variable is made, thus making changes to these in the method does not affect the value of the original variables.
This can be done easily by modifying the for-loop header. An example (a modification of one of the previous examples) follows:
1 int [] scores = {95,93,90,99};
2 for (int i=scores.length-1; i>=0; i--)
3 System.out.println("Index: "+i+", valuenames[i]);
Sometimes, you don't need to iterate through the entire array — for instance when looking for the location of a specific value within an array. You can do so by using the return keyword once you have already found what you were looking for and traversing further through the array would be just a waste of resources.
An example of the use of return
inside a for-loop traversing an array follows. The returnIndex()
method takes in two parameters - an array as well as a string to look up within the array values. It returns an integer — the index number of the array slot where the value is located (and by doing so breaks the loop and exits the method — see line 6). If it has finished traversing through the array and hasn't found what it was looking for, it will use the default return statement — (see line 8) which returns -1
.
1 public static int returnIndex(String[] myArray, String valueToFind)
2 {
3 for (i=0;i<myArray.length;i++)
4 {
5 if myArray[i].equals(valueToFind)
6 return i;
7 }
8 return -1;
9 }
You can limit the looping through an array to any range between 0 and the length of the array -1. It's done by adjusting the for-loop header. An example: say you'd like to print only the first five names from the names array. In case there are less than five student names in the array, it will print them all and stop traversing in order not to generate an ArrayOutOfBoundsException
:
1 String [] names = {"Tomas", "Wonkyu", "Soosan", "Anton"};
2 for (int i=0; (i<5)&&(i<names.length); i++)
3 System.out.println(names[i]);
In the program above I used the AND boolean operator (&&
) to combine two logical tests to determine when to finish the execution of the loop:
i
needs to be lower than 5AND
i
needs to be lower than the length of the loop (this in case my array length is less than 5, so I don't get out of bounds of the array)An enhanced for-loop is a special type of for-loop that can only be used with arrays, arrayLists as well as some other data structures that fall under the so called Collections
(not within the scope of AP CS A).
For-each loops are used only for reading, not modifying array elements.
for (dataType variableName : arrayName)
{
commands_to_repeat; // accessing the current array element through the variableName variable
}
An example of printing all array elements:
1 String [] names = {"Tomas", "Wonkyu", "Soosan", "Anton"};
2 for (String name : names)
3 System.out.println(name);
We can call this type of for-loop as a for-each loop as in pseudocode you could say:
For your AP exam, you need to be familiar with the following algorithms utilizing arrays and traversals:
MIN, MAX
functions in Excel)SUM,AVERAGE,MODE
functions in Excel)COUNTIF
in Excel)For your AP exam, you need to be familiar with the following algorithms utilizing traversals for modifying arrays:
Finding the maximum value in an array - using a returnMax()
method:
static int[] numbers= {5,10,3,15,22}
public static int returnMax(int[] intArray)
{
int max=intArray[0];
for (int Number:intArray)
if (Number>max)
max=Number;
return max;
}
System.out.println("The maximum is: "+returnMax(numbers));
Finding the minimum value in an array - using a returnMin()
method - almost identical to the returnMax()
method - changes are in bold:
static int[] numbers= {5,10,3,15,22}
public static int returnMin(int[] intArray)
{
int min=intArray[0];
for (int Number:intArray)
if (Number < min) // don't forget to change the ">" to "<"
min=Number;
return min;
}
System.out.println("The minimum is: "+returnMin(numbers));
Finding the sum of all values in an array - using a returnSum()
method:
static int[] numbers= {5,10,3,15,22}
public static int returnSum(int[] intArray)
{
int sum=0;
for (int Number:intArray)
sum+=Number;
return sum;
}
System.out.println("The sum is: "+returnSum(numbers));
Finding the mode of all values in an array - using a returnMode()
method:
public class Main
{
public static int returnMode(int[] numbers)
{
int[] frequences=new int[numbers.length];
int mode=numbers[0];
for (int i=0;i<numbers.length;i++)
{
for (int j=i;j<numbers.length;j++)
{
if (numbers[i]==numbers[j])
frequences[i]++;
}
if (frequences[i]>numbers[mode])
mode=numbers[i];
}
return mode;
}
public static void main()
{
int[] numbers={5,4,2,5,4,3,4,5,4,3};
System.out.println(returnMode(numbers));
}
}
public int findHorseSpace(String name)
{
for (int i=0; i<spaces.length;i++)
{
if (spaces[i]!=null && spaces[i].getName().equals(name))
return i;
}
return -1;
}
public void consolidate()
{
for (int i=0;i<spaces.length;i++)
{
for (int j=i;j>0;j--)
{
if (spaces[j-1]==null)
{
spaces[j-1]=spaces[j];
spaces[j]=null;
}
}
}
}
public static int[] firstNumSelfDivisors(int start,int num) {
int numbers[] = new int[num];
int counter=0;
while (counter<num)
{if (isSelfDivisor(start))
{
numbers[counter]=start;
counter++;
}
start++;
}
return numbers;
}
public int limitAmplitude(int limit)
{
int counter=0;
for (int i=0;i<samples.length; i++)
{
if (samples[i]>limit)
{
samples[i]=limit;
counter++;
}
if (samples[i]<-limit)
{
samples[i]=-limit;
counter++;
}
}
return counter;
public void trimSilenceFromBeginning()
{
int counter=0;
while (samples[counter]==0)
counter++;
int trimmedSamples[]=new int[(samples.length-counter)];
for (int i=0;i<trimmedSamples.length;i++)
trimmedSamples[i]=samples[i+counter];
samples=trimmedSamples;
}
public static int[] getCubeTosses(NumberCube cube, int numTosses)
{
int[]tosses = new int[numTosses];
for (int i=0;i<numTosses;i++)
tosses[i]=cube.toss();
return tosses;
}
public static int getLongestRun(int[] values)
{
int currentRunLength=0;
int maxRunLength=0;
int maxRunStart=-1;
for (int i=0;i<values.length-1;i++)
{if (values[i]==values[i+1])
{currentRunLength++;
if (currentRunLength>maxRunLength)
{
maxRunLength=currentRunLength;
maxRunStart=i+1-currentRunLength;
}
}
else
currentRunLength=0;
}
return maxRunStart;
}