Skip to content
Chris Ward edited this page Oct 8, 2022 · 1 revision

Arrays are a group of variables that are all linked together. They have some limitations, they can't be just anything. You have to create them with a set size, all values are the same type, and you access them with an index, often from a loop.

Remember this code from learning Python?

cp.pixels[0] = (100, 0, 0)
cp.pixels[1] = (0, 100, 0)

We accessed the pixels with an index, like 0 or 1. And just like this, Arrays start at zero too.

int[] numbers = new int(3);
String[] colors = new String(4);

In the lines above we created an array of int and an array of String. First we say the type with [] to denote an array. Then we say new and then the type again with the size. Arrays are also objects, and to create an object we use new in Java. We didn't need to use that with String, which is a special object. You didn't expect a programming language to be consistent, did you? More on objects in the next page!

Lets see a complete example:

package examples.g_arrays;

public class IntArray {
    public static void main(String[] args) {
        int[] stuff = new int[3];
        stuff[0] = 22;
        stuff[1] = 51;
        stuff[2] = 99;

        for (int i=0; i < 3; i++) {
            System.out.println(stuff[i]);
        }
        int[] other = new int[] {2, 8, 5, 3, 7};
        other[2] = 555;

        for (int i=0; i < 5; i++) {
            System.out.println(other[i]);
        }
    }
}

Looking at this example you can see two different ways to "initialize" the array - which means to set it's size and sometimes to put values into it. The first way, we give it a size number [3]. Then we assign individual values one by one. The second way we didn't need to provide a number for the size, because Java can tell by the set of numbers we passed to it. This way we don't even have to assign them after. But we can. We can change any of the "spots" in the array when ever we like.

Remember I said that we often use loops to access the array? You have to be very careful you don't use an index value that is too big. Try to set a value to other[20]. What happens? Instead of looping to i < 5, try i < 10. What happens? Do the errors make sense? A little bit? Being able to figure out what error messages mean is an important skill. If you get an error, which you will, (everyone does) being able to figure out why and correct it quickly will make you very happy.

Ok, now do strings. Create or change the program such that the names of the programming team are in an array. Then loop over them and print out all of the names.

Bonus points:

  • Print "Programming Team" first, and "That's all folks" last, but not in the array.
  • Print a number beside the name of each team member increasing from 1 to the number of team members.
  • Print "Captain" beside the name of the student(s) that is/are captain(s).

Ok, we are doing it. We are going to talk about Classes and Objects now.

Clone this wiki locally