What is an Array?
An array is an ordered collection of items stored in adjacent memory locations. It has a fixed capacity, and can only store items of the same datatype. There are many ways to initialize an array, show below is an example program which initializes an array of integers in 3 different ways.
public class ArrayDemo {
public static void main(String[] args) {
int[] arr1 = new int[5]; // Initializes arr1 to [0,0,0,0,0]
int[] arr2 = {0, 1, 2, 3, 4}; // Initializes arr2 to [0,1,2,3,4]
int[] arr3 = new int[] {0, 1, 2, 3, 4}; // Initializes arr3 to [0,1,2,3,4]
}
}
2D Arrays
A 2D array is an array of arrays. 2D arrays are useful when storing complex data. They are also useful for modelling things like 2D surfaces and matrices.
Ways to initialize 2D arrays:
public class ArrayDemo {
public static void main(String[] args) {
type[][] arr = new type[rows][columns]; // All elements set to default values (usually either 0 or null)
type[][] arr = {{element1, element2, element3}, {element4, element5, element6}}; // Elements set to preset values
}
}
Why use Arrays?
Arrays are useful for a variety of different reasons, mainly to store and organize large amounts of data. For example, if a teacher wants to store the test scores of 30 students, instead of making 30 different double variables and storing a different student's test score in each variable, they can just make an array of doubles with length 30 and store a test score in each indice. Arrays can also be easily sorted, so if the teacher wants to order the student's test scores from highest to lowest to find the top 3 highest scores in their class, they can simply sort the double array and get the first 3 values.Accessing Elements in an Array
Elements of an array be accessed by their index, which is a number that indicates the position of the element in an array. For example, the index of the first element in an array is 0, the index of the second element is 1, 2 for the third, 3 for the fourth, etc. To access an element in an array, simply specify the name of the array and the index in square brackets. For example,System.out.print(arr[2]);
prints the third element in arr
and arr[2] = "three";
sets the third element of arr
to "three"
, given that arr
is an array of strings. Trying
to access an element outside of an array's range will throw an ArrayIndexOutOfBoundsException
.
Show below is a demonstration of this functionality.
public class AccessingElements {
public static void main(String[] args) {
String[] arr = new String[] {"zero","one","two","three","four"}; // Initializes arr to [0,1,2,3,4]
System.out.print(arr[2]); //"two"
arr[2] = "five"; //Sets the third element in arr to "five"
System.out.print(arr[2]); //"five"
System.out.println(arr[5]); //ArrayIndexOutOfBoundsException
}
}