int ArrayUse int arrays: create them and loop over them with different syntaxes.
This page was last reviewed on Jan 20, 2024.
Int arrays. Integers 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.
Shows an int 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.
ArrayList int
Create arrays. This program creates 2 int arrays. It then loops over the arrays with a for-loop, printing their values to the Console window.
Part 1 Here we see the short, initializer syntax—we use curly brackets. Ints are specified in one line.
Part 2 We initialize an array in separate statements. This is the "alternative" array, but this style is standard and clear.
Tip The for-loop syntax can be used on an int array in 2 ways—with a ":" over elements, or in the standard indexing syntax.
Shows an int array
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
Return int array. A 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
Array in 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.
Start AddResidentAt increments the apartmentIds array at a specified index. In a real program, it might check for a valid index.
Next RemoveResidentAt is the same style of method as addResidentAt but it subtracts from the element at the array index.
Finally 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.
Note Even in a 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.
However If the array's size is uncertain, we must use an 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)
Clone. 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.
So When a cloned array is modified, the original does not reflect those changes.
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
Ints are sometimes used alone. But often we use many elements together. In an int array we accommodate many ints into a single class—this makes ints more convenient.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jan 20, 2024 (edit).
© 2007-2024 Sam Allen.