Int
arraysIntegers are everywhere in the modern world: we use them for counting, for data representation. They can be used alone. But often ints are best kept together in an array.
An array cannot be resized dynamically. For a collection that grows are you need more elements, consider an ArrayList
. The Integer class
is helpful.
This program creates 2 int
arrays. It then loops over the arrays with a for
-loop, printing their values to the Console
window.
short
, initializer syntax—we use curly brackets. Ints are specified in one line.for
-loop syntax can be used on an int
array in 2 ways—with a ":" over elements, or in the standard indexing syntax.public class Program { public static void main(String[] args) { // Part 1: create int array with 4 elements. int[] values = { 10, 20, 30, 40 }; // ... Loop over the array's elements. for (int value : values) { System.out.println(value); } // Part 2: create int array with 3 elements in separate statements. int[] alternative = new int[3]; alternative[0] = 100; alternative[1] = 200; alternative[2] = -100; // ... Use for-loop to access all elements. for (int i = 0; i < alternative.length; i++) { System.out.println(alternative[i]); } } }10 20 30 40 100 200 -100
int
arrayA method can return an array. Here we introduce a getEmployees
method—it internally populates an array and then returns it.
public class Program { static int[] getEmployees() { // Create an int array and return it. int[] array = new int[6]; array[0] = 9; array[1] = 11; array[2] = 15; array[3] = 19; array[4] = 29; array[5] = 55; return array; } public static void main(String[] args) { // Loop over an array returned by a method. for (int e : getEmployees()) { System.out.println(e); } } }9 11 15 19 29 55
class
Arrays can be used as fields in classes. This fits well with the object-based design in many Java programs. Here, we place an apartmentIds
array in the Building class
.
AddResidentAt
increments the apartmentIds
array at a specified index. In a real program, it might check for a valid index.RemoveResidentAt
is the same style of method as addResidentAt
but it subtracts from the element at the array index.GetOccupancyAt
returns the value of the element at an index. In main, we use it and the other two methods.class Building { int[] apartmentIds = new int[10]; public void addResidentAt(int id) { // Add to the array at this index. apartmentIds[id]++; } public void removeResidentAt(int id) { // Subtract from element value. apartmentIds[id]--; } public int getOccupancyAt(int id) { // Return element value. return apartmentIds[id]; } } public class Program { public static void main(String[] args) { // Create a Building. // ... Some residents move in and one leaves. Building b = new Building(); b.addResidentAt(5); b.addResidentAt(3); b.addResidentAt(9); b.removeResidentAt(5); // Display occupancy of apartments. for (int i = 0; i < 10; i++) { System.out.println(Integer.toString(i) + ": " + b.getOccupancyAt(i)); } } }0: 0 1: 0 2: 0 3: 1 4: 0 5: 0 6: 0 7: 0 8: 0 9: 1
NullPointerException
An int
array is a reference to a memory region—in this way it is similar to other classes. The reference can be null
. We must guard for this case.
for
-loop, we must first check for a null
array. A NullPointerException
will otherwise occur.public class Program { public static void main(String[] args) { int[] array = null; // We must first check for null before looping over an array. // ... This causes a runtime error. for (int value : array) { System.out.println(value); } } }Exception in thread "main" java.lang.NullPointerException at program.Program.main(Program.java:9)
ArrayIndexOutOfBoundsException
With an array of any type, we must be careful to avoid checking element ranges. Sometimes programs can omit these checks for performance.
if
-check to ensure an exception does not occur.public class Program { public static void main(String[] args) { // This array has just 5 elements. // ... So the only valid indexes are 0, 1, 2, 3 and 4. int[] array = { 40, 50, -60, -70, 80 }; // This causes an exception. array[10] = 1000; } }Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 at program.Program.main(Program.java:7)
This method is helpful with int
arrays. It copies all the elements from the original array into a new one. The arrays will occupy different memory regions.
public class Program { public static void main(String[] args) { int[] items = { 10, 20, 40 }; // Clone the int array. // ... All the elements are copied into a new array. int[] copy = items.clone(); // When the copy is modified, the original "items" is not affected. copy[0] = -100; System.out.println(items[0]); System.out.println(copy[0]); } }10 -100
But often we use many elements together. In an int
array we accommodate many ints into a single class
—this makes ints more convenient.