Programming For Non-Techies - Arrays

Programming For Non-Techies - Arrays

Programming For Non-Techies is a weekly feature for non-techies to learn to program every Friday.  If it’s your first time here please review the previous lessons in the archives to get caught up.  This week’s lesson continues the discussion about variables and we will look at Arrays.   If you’re a non-techie and you want to learn to program, or maybe you want a job in tech and need a better understanding of programming, these posts will help you!

If you’re new here, I strongly suggest looking at the previous programming posts since they build on each other.

What is an Array?

An Array is a container that holds a fixed number of a single type.  It’s sometimes called a Primitive Array since there are other types, such as ArrayList, that are similar but also very different.  The type of each item in the Array must be the same and the length of the Array cannot change.  If you create an Array with a length of 10, it can only hold 10 items.

Array vs ArrayList

An Array is more efficient than an ArrayList.  It’s also more limited in its uses.  An ArrayList is, basically, a wrapper around an Array that provides much more functionality, but at a resource cost.  I’ll talk more about ArrayList next week when I discuss Interfaces.  For now, just know that there are several different ways to handle an array of data and you choose the appropriate one depending on the problem you’re trying to solve.

Let’s look at Java code

In the example, I create an Array of type int with a length of 3 and assign it to a variable named ‘intArray’.  Last week you saw the ‘new’ keyword used for classes and you need it here too, for Arrays.  Once the array is created, it’s populated with data.  The first location in an Array is 0 and each location after that increases by 1.  Then, to print out all the values a for loop is used.

Try running this in Eclipse and feel free to experiment.  For example, try adding a line like this:  intArray[3] = 3;

public class ArrayExample {

	public static void main(String[] args) {
		int[] intArray = new int[3];
		
		intArray[0] = 22;
		intArray[1] = 33;
		intArray[2] = 44;
		
		for(int i=0; i < intArray.length; i++) {
			System.out.println("intArray[" + i + "] = " + intArray[i]);
		}
	}
}

Leave a Comment