Instructional Material: Arrays

Printer-friendly version

An array is a special object used to store a list of variables of the same data type. An array is defined like this:

This statement defines and then creates an array of 3 integer variables (or elements) which will be addressed as a list. The new keyword defines the size of the array. We can then put values in the array and access them with an index value (position) in the array. Arrays are indexed starting at zero:

Note that we can initialize array values with the new keyword:

Arrays may have more than one dimension:

For loops are especially useful in processing arrays:

This will print out:

row 0 col 0 = 5
row 0 col 1 = 10
row 1 col 0 = 15
row 1 col 1 = 20

Notice the array has a built-in field called length that tells the size of the array.

Arrays are fixed in their dimensions once created so the array size can't be changed. If you need dynamic array sizing, that is, you want to change the size of the array as your program proceeds, you can use a class called an ArrayList. The ArrayList is defined in the java.util package. An ArrayList has methods that allow you to add and remove elements on the fly:

String s will contain "A different String object". Why? Because when we removed element zero, the rest of the elements shifted down.

ArrayLists have a number of methods you can use to manipulate the array. Note that the ArrayList can only contain object instance references (no primitives). Also note that when we created the ArrayList, we specified the type of object that would be contained in the ArrayList.

The for statement has a special case called for-each that applies to arrays and collections (next lesson). This special for statement will automatically provide each element in an array to your code in the for statement or block:

ArrayList is just one of many types of Lists (called Collections) available in the Java API.

Here is a video about Arrays. Here is a detailed discussion of Arrays.

Here is the example code on CodingGround. Add code to the example to add up all the elements in array x1 using a for loop and print the result. Add another for loop to print the strings in ArrayList a1.

 

Material Type: 
Lecture/Presentation
Education Level: 
HW Platform: 
SW Platform: 
Interactivity Style: 
Audience: