Lesson: Arrays

Overview: 
Explore variable arrays in Java.
Objectives: 

Understand what arrays are and how to use them.

Content: 

An array is 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

Arrays are fixed in thier 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 special 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.

ArrayList is just one of many types of Lists 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.

 

Navigation: